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.
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.
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); }, []); ...
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/
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With