如何重置 setInterval 计时器?

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

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

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

151066 次浏览

Once you clear the interval using clearInterval you could setInterval once again. And to avoid repeating the callback externalize it as a separate function:

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

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

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/

Here's Typescript and Nuxt 3 version if anyone's interested :]

Composable useInterval.ts

useInterval.ts

export function useInterval (callback: CallableFunction, interval: number): Interval { // Argument interval = milliseconds
return new Interval(callback, interval)
}


class Interval {
private timer = null


constructor (private callback, private interval) {
}


start () {
this.timer = setInterval(this.callback, this.interval)
}


stop () {
clearInterval(this.timer)
this.timer = null
}


restart (interval = 0) {
this.stop()


if (interval) {
this.interval = interval
}


this.start()
}
}

Example usage

const interval = useInterval(function() {
// your function here
}, 5000);


// Reset the interval and set it to 10s
interval.reset(10000);


// Stop the interval
interval.stop();


// Start the interval
interval.start();