setInterval 和clearInterval 未按预期工作
我有这个函数,它充当加载框,使用 setInterval 来更改背景图像,从而创建闪烁效果。
function loading() {
clearInterval(start);
var i = 0;
function boxes() {
in_loading = ".in_loading:eq(" + i + ")";
$(".in_loading").css("background", "url(images/load_bar_green.png) no-repeat");
$(in_loading).css("background", "url(images/load_bar_blue.png) no-repeat");
if(i == 3) {
i = 0;
} else {
i++;
}
}
var start = setInterval(function() {
boxes();
}, 350);
}
但即使使用 clearInterval
如果我多次点击它,闪烁也会出现故障。我尝试移除盒子,隐藏它们,但我似乎无法清除“缓冲区”?有什么想法吗?
I have this function which acts as a loading box using setInterval
to change the background images which creates a flashing effect.
function loading() {
clearInterval(start);
var i = 0;
function boxes() {
in_loading = ".in_loading:eq(" + i + ")";
$(".in_loading").css("background", "url(images/load_bar_green.png) no-repeat");
$(in_loading).css("background", "url(images/load_bar_blue.png) no-repeat");
if(i == 3) {
i = 0;
} else {
i++;
}
}
var start = setInterval(function() {
boxes();
}, 350);
}
But even with clearInterval
if I click on it more than once the flashing goes out of order. I tried removing the boxes, hiding them but I can't seem to get the 'buffer' cleared? Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它一直闪烁的原因是每次调用
loading
时都会创建一个新变量start
,因此clearInterval
实际上什么也没做。您也不应该在loading
中使用boxes
函数,因为它执行相同的操作,每次都会创建一个新的
。脚本执行的时间越长,这就会增加很多延迟。boxes
函数调用加载The reason why it keeps flashing is because every time
loading
gets called it creates a new variablestart
, soclearInterval
is actually doing nothing. You also shouldn't have theboxes
function withinloading
because it is doing the same thing, creating a newboxes
function every timeloading
is called. This will add a lot of lag the longer the script executes.函数声明被“提升”到其作用域的顶部,这就是混乱执行顺序的原因。检查这个: http://javascriptweblog.wordpress.com /2010/07/06/函数声明与函数表达式/
Function declarations get "hoisted" to the top of their scope, this is what is messing the execution order. Check this: http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
原因是每次调用加载时,它都会创建一个新的 Interval 或新的
var start
。因此,如果您单击它两次,那么您就有两个东西在操作相同的数据。因此,您需要将var start
放在函数外部,将clearInterval
放在函数内部。因此,每次调用加载时,它都会清除间隔并创建一个新间隔。The reason is every time you call loading it creates a new Interval or new
var start
. So if you click it twice, then you have two things manipulating the same data. So you need to have thevar start
outside of the function and theclearInterval
inside. So every time you call loading it clears the interval and creates a new one.也许你应该看看这个 Jquery 插件,它似乎很好地管理间隔。
Jquery 计时器插件
maybe you should take a look at this Jquery Plugin , it seems to manage intervals very well .
Jquery Timers Plugin