Javascript - Reset setInterval back to 0

How to reset the setInterval timer back to 0?

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

I tried clearInterval (myTimer), but this completely stopped the interval. I want it to restart from 0.

+47
javascript reset setinterval restart
Nov 14 '11 at 18:42
source share
2 answers

If, during a reboot, you intend to start a new 4-second interval at this point, 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 can also use a small timer object that offers a reset function:

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

Using:

 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/

+92
Nov 14 '11 at 18:46
source share

Once you clear the interval using clearInterval , you can setInterval again. And to avoid repeating the callback, make 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); 
+8
Nov 14 '11 at 18:45
source share



All Articles