如何重置setInterval计时器?


81

如何将setInterval计时器重置为0?

var myTimer = setInterval(function() {
  console.log('idle');
}, 4000);

我试过了,clearInterval(myTimer)但这完全停止了间隔。我希望它从0重新启动。

Answers:


171

如果通过“重新启动”表示此时要开始一个新的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);

您还可以使用一个带有重置功能的小计时器对象:

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

用法:

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

工作演示:https//jsfiddle.net/jfriend00/t17vz506/


美丽的对象。当我看到有人在javascript中使用OOP时,我总是感觉很好!谢谢!
Fortin

12

一旦清除间隔,clearInterval您就可以setInterval再次使用。为了避免重复执行回调,请将其外部化为一个单独的函数:

var ticker = function() {
    console.log('idle');
};

然后:

var myTimer = window.setInterval(ticker, 4000);

然后当您决定重新启动时:

window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);

但是如何?clearInterval(myTimer)然后setInterval(myTimer,4000)不起作用:(
Rik de Vos

@RikdeVos,为什么不起作用?也不是setInterval(myTimer, 4000),应该是setInterval(ticker, 4000);
Darin Dimitrov
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.