javascript – 如何重置setInterval计时器?

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

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

我尝试了clearInterval(myTimer)但完全停止了间隔.我希望它从0重新启动.

解决方法:

如果通过“重新启动”,您的意思是此时开始新的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 interval, stop current interval
    this.reset = function(newT) {
        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初级——Window对象的定时器


下一篇:javascript – setInterval会导致浏览器挂起吗?