How to count active javascript timeouts? How to count active javascript timeouts? ajax ajax

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.


Another approach could be like this

const timeoutIndexThen = setTimeout(() => {});// Some code that might call timeouts...const timeoutIndexNow = setTimeout(() => {});const countOfTimeoutsFiredSinceThen = timeoutIndexNow - timeoutIndexThen - 1;

It is based on the fact that each timeout will return a number that is greater by 1 on each call.

So we create some dummy timeout just to get this number at some point.

Then, after a while we call it again and we get a new number. Difference between those numbers is how many times interval was called in between.

Downside of this is that you have to actually create the timeout. Upside is that you don't have to modify original function.