Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reset the setInterval timer?

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.

like image 386
Rik de Vos Avatar asked Nov 14 '11 18:11

Rik de Vos


People also ask

Do I need to clear setInterval?

SetInterval() does not change the speed that you pass it. If whatever it is doing speeds up each time that you call SetInterval(), then you have multiple timers which are running at the same time, and should open a new question. Make sure you are really stopping it.

How do you clear the interval in react native?

Clearing setInterval in React To stop an interval, you can use the clearInterval() method. ... useEffect(() => { const interval = setInterval(() => { setSeconds(seconds => seconds + 1); }, 1000); return () => clearInterval(interval); }, []); ...


2 Answers

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/

like image 74
jfriend00 Avatar answered Oct 14 '22 01:10

jfriend00


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);
like image 43
Darin Dimitrov Avatar answered Oct 14 '22 02:10

Darin Dimitrov