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);
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() {
Working demo: https://jsfiddle.net/jfriend00/t17vz506/
jfriend00 Nov 14 '11 at 18:46 2011-11-14 18:46
source share