为什么 setTimeout 会“排队”?调用 stopTimeout 时回调?
我创建了一个滑块,它可以与下一个/上一个箭头一起用于计时器。
单击箭头时,我想停止自动计时器,然后在最后一次单击后重新启动 x-time。不幸的是,我目前所拥有的似乎是计时器,所以如果多次单击箭头,自动计时器会重新启动,但移动速度非常快......
我似乎无法解决这个问题 - 如何仅维护一个 setInterval 并避免它们累积。 ..
非常感谢任何帮助 - 下面粘贴的代码
var int = setInterval(back, autoTimerTime);
//down arrow
$('.arrow-down').click(function(){
if (!$('ul.as-thumbs').is(':animated')) {
back();
clearInterval(int);
clearTimeout(timeout);
var timeout = setTimeout(function() {
var int = setInterval(back, autoTimerTime);
}, 8000);
}
});
I've created a slider which works on a timer along with next/prev arrows.
When an arrow is clicked I want to stop the auto timer then re-start x-time after the last click. Unfortunately what I have currently seems to que timers so if the arrow is clicked multiple times the auto timer restarts but moves really fast...
I can't seem to work it out - how to maintain just one setInterval and avoid them building up...
Any help greatly appreciated - code pasted below
var int = setInterval(back, autoTimerTime);
//down arrow
$('.arrow-down').click(function(){
if (!$('ul.as-thumbs').is(':animated')) {
back();
clearInterval(int);
clearTimeout(timeout);
var timeout = setTimeout(function() {
var int = setInterval(back, autoTimerTime);
}, 8000);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须将对
timout
的引用放置在click
处理程序的公共范围内,如下所示。当在新作用域中使用var
时,会在本地作用域[1] 中再次声明该变量。[1]:局部/全局变量图解简而言之
,以
var
关键字为前缀的变量在局部作用域中再次声明。在 JavaScript 中,可以通过使用function() { .. }
包围一个块来创建新作用域。当请求变量时,引擎首先在当前(本地)范围中查找。如果该变量存在,则使用该变量。
否则,将检查父作用域等,直到找到变量。如果在顶部(全局范围)没有找到该变量,则会发生以下情况:
ReferenceError
。foo = 1
,该变量将在全局范围内声明@Nitpicks:不考虑
let
)ReferenceError
。You have to place the reference to the
timout
in the common scope of theclick
handlers, as shown below. Whenvar
is used in a new scope, the variable is declared again, in the local scope[1].[1]: Illustrated explanation of local/global variables
In short, variables prefixed by the
var
keyword are declared again in the local scope. In JavaScript new scope can be created by surrounding a block byfunction() { .. }
.When a variable is requested, the engine first looks in the current (local) scope. If the variable is present, this variable is used.
Otherwise, the parent scope is examined, etc, etc, until the variable is found. If the variable is not found at the top (global scope), the following will happen:
ReferenceError
will be thrown.foo = 1
, the variable will be declared at the global scope@Nitpicks:
let
not taken into account)ReferenceError
will be thrown.clearTimeout(timeout);
永远不会起作用,因为“timeout”不是全局变量。您在函数内定义它。clearTimeout(timeout);
will never work because "timeout" is not a global variable. You're defining it WITHIN the function.