Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count active javascript timeouts?

I am using Selenium to test a web app that uses Dojo, and it uses java script to display certain elements. I want to wait until all of the elements are desplayed before I try to manipulate the page, however I am having trouble.

I have started by waiting for the dojo inFlight variable to be 0, this says that all ajax has finished. This doesn't always work because it seems to do some things on a timeout afterwards.

I have also tried repeatedly looking for the element, but this isn't too nice, as perhaps there is some javascript later which will use this field in some way.

So basically I want a method (in firefox at least) to query the javascript waiting to run on a setTimeout (or setInterval) I could even cope with a way of wrapping the built in call through a function of my own just to keep track of this.

Any thoughts or suggestions appreciated!

like image 688
Sam Marland Avatar asked Aug 18 '11 08:08

Sam Marland


2 Answers

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");
like image 186
Ross Patterson Avatar answered Sep 28 '22 01:09

Ross Patterson


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.
like image 40
treecoder Avatar answered Sep 28 '22 02:09

treecoder