Question

My question is: is there a unique way to reset timers without knowing their ID in Javascript? I tried using this code:

var maxId = setTimeout(function(){}, 0);

for(var i=0; i < maxId; i+=1) { 
    clearTimeout(i);
}

I'm aware this would search for any timer and clear any timer, but nothing happens and I think the console even gives me an error when I use it as a bookmarklet. Also, the value of the timer is stored in innerHTML, as such:

<div id="timer">

    <div id="timer-minutes" class="timer-fields">00:00</div>

</div>
Was it helpful?

Solution

A unique way to look at this problem is to override the default functionality of setTimeout. By augmenting the function you can then tap into all uses of setTimeout on the page. Then you can simply create a new method to clear all timeouts.

In the code below, I hot-wire the built-in function (setTimeout) with my own version. As long as this code executes before other scripts on the page, I then can keep track of all invocations of the function on the page. Perhaps you could even store the setTimeouts by callee.

(function(win)
{
  var _originalSetTimeout = setTimeout; //Store built-in function
  var timers = []; //Maintain a collection of timers

  win.setTimeout = function(func, delay) //Hijack the built-in function with your own
  {
    var timer = _originalSetTimeout(func, delay); //Invoke the built in
    timers.push(timer);  //Store the timer to your private array
  };

  win.clearAllTimeouts = function()  //Create a new function on the window for resetting all timers
  {
    for(var i=0,length=timers.length;i<length;i++)
      {
        win.clearTimeout(timers[i]);
      }
  };
}(window));

Once this function is wired up you then can test with the following code:

var x=0;
function Test()
{
  x++;
  console.log('test: ' + x);
  setTimeout(Test, 1000);

  if(x === 5)
  {
    clearAllTimeouts();
    console.log('all timeouts cleared!');
  }
}
Test();

The counter will log up to 5, then once it's it the clearAllTimeouts() function is invoked.

See it in action here: http://jsbin.com/bulayuro/1/edit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top