在函数中重置 setInterval,范围是全局的..?
问题:当我在函数中声明clearInterval()/setInterval()或clearTimeout()/setTimeout()时,它什么也不做。我必须重置它的原因是用户可以单击重置计时器。
我尝试过的:我想要一个函数每 3 秒执行一次(因此我使用 setInterval() 与 setTimeout() ),并在单击时重置该计时器。我尝试通过使用clearTimeout() & 来使用setTimeout()每次执行函数结束时 setTimeout() 。结果:执行一次。
下面的代码与setInterval相同。结果:它循环并且永不重置。
// Declare variables as global
var varTimerSpeed = 3000;
var varTimerInterval;
varTimerInterval = setInterval("someFunction()", varTimerSpeed);
function someFunction() {
// Reset timer
clearInterval(varTimerInterval);
varTimerInterval = setInterval("someFunction()", varTimerSpeed);
}
// Call the function
$(".class").live("click",function() { someFunction(); });
我在 someFunction() 中进行了其他正确执行的操作,因此我知道单击处理程序正在工作。
The problem: When I declare clearInterval()/setInterval() or clearTimeout()/setTimeout() within a function, it does nothing. The reason I must reset it is that the user may click to reset the timer.
What I've tried: I want a function to execute every 3 seconds (hence why I'm using setInterval() vs. setTimeout()), and reset that timer on click. I've tried using setTimeout() by having it clearTimeout() & setTimeout() at the end of every time the function is executed. RESULT: It executes once.
The below code is the same with setInterval. RESULT: It loops and never resets.
// Declare variables as global
var varTimerSpeed = 3000;
var varTimerInterval;
varTimerInterval = setInterval("someFunction()", varTimerSpeed);
function someFunction() {
// Reset timer
clearInterval(varTimerInterval);
varTimerInterval = setInterval("someFunction()", varTimerSpeed);
}
// Call the function
$(".class").live("click",function() { someFunction(); });
I have other things going on in someFunction() that execute properly so I know that the handler for click is working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望
someFunction
按一定时间间隔运行,但在单击.class
元素时将其清除并重置,则不要清除someFunction 内的时间间隔
。只需在单击处理程序中清除并重新启动它即可。
If you want the
someFunction
to run at an interval, but have it clear and reset when.class
element is clicked, then don't clear the interval insidesomeFunction
.Just clear and restart it in the click handler.
这个稍微修改过的 jsFiddle 似乎工作正常:http://jsfiddle.net/jfriend00/GgQBu/。
This slightly modified jsFiddle seems to work fine: http://jsfiddle.net/jfriend00/GgQBu/.