phantomjs/examples/waitfor.js

41 lines
1.4 KiB
JavaScript
Raw Normal View History

2011-04-05 02:24:50 +04:00
/**
* Wait until the test condition is true or a timeout occurs. Useful for waiting
* on a server response or for a ui change (fadeIn, etc.) to occur.
*
* @param testFx javascript condition that evaluates to a boolean,
* it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
* as a callback function.
* @param message a message to show on failure
2011-04-23 15:05:43 +04:00
* @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
2011-04-05 02:24:50 +04:00
*/
function waitFor(testFx, message, timeOutMillis) {
2011-04-23 15:05:43 +04:00
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000;
2011-04-05 02:24:50 +04:00
var start = new Date().getTime();
var condition = false;
while(new Date().getTime() - start < maxtimeOutMillis) {
2011-04-23 15:00:00 +04:00
phantom.sleep(250);
condition = (typeof(testFx) == "string" ? eval(testFx) : testFx());
if(condition) break;
2011-04-05 02:24:50 +04:00
}
if(!condition) {
2011-04-23 15:00:00 +04:00
throw Error("Timeout: " + message);
2011-04-05 02:24:50 +04:00
}
console.log("+++ waitUntil finished in " + (new Date().getTime() - start) + " millis.");
}
// example use:
if(!phantom.state) {
// load a twitter page
phantom.state = "loaded";
phantom.open("http://twitter.com/#!/senchainc");
2011-04-05 02:24:50 +04:00
} else {
// click the "sign in" link
$(".signin-link").click();
2011-04-05 02:24:50 +04:00
// wait for the sign in dialog to pop up
waitFor(function() {
return $("#signin-dropdown").is(":visible");
2011-04-05 02:24:50 +04:00
}, "The sign-in dialog should be visible");
phantom.exit();
}