2 * Wait until the test condition is true or a timeout occurs. Useful for waiting
3 * on a server response or for a ui change (fadeIn, etc.) to occur.
5 * @param testFx javascript condition that evaluates to a boolean,
6 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
7 * as a callback function.
8 * @param onReady what to do when testFx condition is fulfilled,
9 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
10 * as a callback function.
11 * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
15 function waitFor(testFx, onReady, timeOutMillis) {
16 var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
17 start = new Date().getTime(),
19 interval = setInterval(function() {
20 if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
21 // If not time-out yet and condition not yet fulfilled
22 condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
25 // If condition still not fulfilled (timeout but condition is 'false')
26 console.log("'waitFor()' timeout");
29 // Condition fulfilled (timeout and/or condition is 'true')
30 console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
31 typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
32 clearInterval(interval); //< Stop this interval
35 }, 250); //< repeat check every 250ms
39 var page = require('webpage').create();
41 // Open Twitter on 'sencha' profile and, onPageLoad, do...
42 page.open("http://twitter.com/#!/sencha", function (status) {
43 // Check for page load success
44 if (status !== "success") {
45 console.log("Unable to access network");
47 // Wait for 'signin-dropdown' to be visible
49 // Check in the page if a specific element is now visible
50 return page.evaluate(function() {
51 return $("#signin-dropdown").is(":visible");
54 console.log("The sign-in dialog should be visible now.");