How to count active javascript timeouts?

Every function in JavaScript can be replaced. Consider something like this:

window.originalSetTimeout = window.setTimeout;

window.setTimeout = function(func, delay, params) {
    window.timeoutCounter++;
    window.originalSetTimeout(window.timeoutCallback, delay, [func, params]);
}

window.timeoutCallback = function(funcAndParams) {
    window.timeoutCounter--;
    func = funcAndParams[0];
    params = funcAndParams[1];
    func(params);
}

Then:

selenium.waitForCondition("window.timeoutCounter == 0");

Whenever you call setTimeout of setInterval -- a timer id is returned.

  1. Save that timer id in an array
  2. Inside the function that you're calling on the timeout, pop that timer id off the array. Because we have to remove that id from the array as soon as the timer ends.
  3. Any time you want to check the no. of active timers, just query the length of that array.