Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  61] [ 2]  / answers: 1 / hits: 158673  / 13 Years ago, mon, november 14, 2011, 12:00:00

How do I reset a setInterval timer back to 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.


More From » setinterval

 Answers
42

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/


[#89132] Saturday, November 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anyssaarielles

Total Points: 415
Total Questions: 107
Total Answers: 92

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
;