重新启动 setInterval
所以我有一个计时器,每 5 秒轮换一组图像。因此,我在文档启动时运行它。
$(document).ready(function() {
var intervalID=setInterval(function(){
rotate();
}, 5000);
});
旋转功能只是旋转图像。但是,我还允许用户手动选择他们正在查看的图像。因此,我需要取消 SetInterval,然后再次在 5 秒处重新开始
我想做的是取消间隔,然后通过这样做重新开始
$('a').click(function(){
clearInterval(intervalID);
intervalID=setInterval(function(){
rotate();
}, 5000);
});
但是,代码似乎没有像我一样重置间隔曾经希望过。
So I have a timer rotates a set of images ever 5 seconds. Therefore, I am running this upon document launch.
$(document).ready(function() {
var intervalID=setInterval(function(){
rotate();
}, 5000);
});
The Rotate function simply just rotates the images. However, I also allow the user to manually select what image they are looking at. Because of this I need to cancel the SetInterval and then start it over back at 5 seconds again
What I am trying to do is cancel the interval then start it over by doing this
$('a').click(function(){
clearInterval(intervalID);
intervalID=setInterval(function(){
rotate();
}, 5000);
});
However, the code doesn't seem to reset the interval like I had hoped.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
intervalID
变量在.ready()
范围内声明,则以下内容应该有效(未经测试):If the
intervalID
variable is declared within the.ready()
scope, the following ought to work (untested):只需在所有函数之外和之上声明它即可使
intervalID
成为全局变量。使用您当前的代码,其范围仅限于
$(document).ready()
方法,因此它可能会导致您描述的问题。Just make
intervalID
be global variable by declaring it outside and above all functions.With your current code its scope is limited to
$(document).ready()
method so it might cause the problem you describe.好吧,看起来您是在
.ready()
处理程序的匿名函数中本地声明interverID
。我实际上想知道为什么您在点击事件处理程序中没有遇到引用错误,因为在那里无法知道intervalID
。您需要确保此变量可用并且对于两个函数都有一个共享上下文。最简单的方法是,在脚本周围创建一个匿名自调用方法,并声明该变量超出范围。
Well, it looks like you are declaring
interverID
locally within the anonymous function from your.ready()
handler. I'm actually wondering why you don't face a Reference error in your click-event handler, sinceintervalID
cannot be known there.You need to make sure that this variable is available and does have a shared context for both functions. Easiest way to go, create an anonymous self invoking method around your script and declare that variable out of scope.