Javascript 如何重置 setInterval 计时器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8126466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I reset the setInterval timer?
提问by Rik de Vos
How do I reset a setInterval
timer back to 0?
如何将setInterval
计时器重置回 0?
var myTimer = setInterval(function() {
console.log('idle');
}, 4000);
I tried clearInterval(myTimer)
but that completely stops the interval. I want it to restart from 0.
我试过了,clearInterval(myTimer)
但这完全停止了间隔。我希望它从0重新启动。
回答by jfriend00
If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.
如果“重新启动”是指此时开始新的 4 秒间隔,则必须停止并重新启动计时器。
function myFn() {console.log('idle');}
var myTimer = setInterval(myFn, 4000);
// Then, later at some future time,
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);
You could also use a little timer object that offers a reset feature:
您还可以使用一个提供重置功能的小计时器对象:
function Timer(fn, t) {
var timerObj = setInterval(fn, t);
this.stop = function() {
if (timerObj) {
clearInterval(timerObj);
timerObj = null;
}
return this;
}
// start timer using current settings (if it's not already running)
this.start = function() {
if (!timerObj) {
this.stop();
timerObj = setInterval(fn, t);
}
return this;
}
// start with new or original interval, stop current interval
this.reset = function(newT = t) {
t = newT;
return this.stop().start();
}
}
Usage:
用法:
var timer = new Timer(function() {
// your function here
}, 5000);
// switch interval to 10 seconds
timer.reset(10000);
// stop the timer
timer.stop();
// start the timer
timer.start();
Working demo: https://jsfiddle.net/jfriend00/t17vz506/
回答by Darin Dimitrov
Once you clear the interval using clearInterval
you could setInterval
once again. And to avoid repeating the callback externalize it as a separate function:
一旦您清除了间隔,clearInterval
您就可以setInterval
再次使用。为了避免重复回调,将其外部化为一个单独的函数:
var ticker = function() {
console.log('idle');
};
then:
然后:
var myTimer = window.setInterval(ticker, 4000);
then when you decide to restart:
然后当您决定重新启动时:
window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);