重新启动setInterval [英] restarting a setInterval

查看:137
本文介绍了重新启动setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个计时器旋转一组图像5秒钟。因此,我在文档启动时运行它。

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);
});

旋转功能只是旋转图像。但是,我还允许用户手动选择他们正在查看的图像。因此我需要取消SetInterval,然后再次在5秒后重新启动它

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.

推荐答案

只需将 intervalID 设为全局变量,方法是将其声明为外部及以上所有函数。

Just make intervalID be global variable by declaring it outside and above all functions.

使用当前代码,其范围仅限于 $(文档).ready()方法所以它可能会导致你描述的问题。

With your current code its scope is limited to $(document).ready() method so it might cause the problem you describe.

这篇关于重新启动setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆