waitfor.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  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.
  4. *
  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.
  12. */
  13. "use strict";
  14. function waitFor(testFx, onReady, timeOutMillis) {
  15. var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
  16. start = new Date().getTime(),
  17. condition = false,
  18. interval = setInterval(function() {
  19. if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
  20. // If not time-out yet and condition not yet fulfilled
  21. condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
  22. } else {
  23. if(!condition) {
  24. // If condition still not fulfilled (timeout but condition is 'false')
  25. console.log("'waitFor()' timeout");
  26. phantom.exit(1);
  27. } else {
  28. // Condition fulfilled (timeout and/or condition is 'true')
  29. console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
  30. typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
  31. clearInterval(interval); //< Stop this interval
  32. }
  33. }
  34. }, 250); //< repeat check every 250ms
  35. };
  36. var page = require('webpage').create();
  37. // Open Twitter on 'sencha' profile and, onPageLoad, do...
  38. page.open("http://twitter.com/#!/sencha", function (status) {
  39. // Check for page load success
  40. if (status !== "success") {
  41. console.log("Unable to access network");
  42. } else {
  43. // Wait for 'signin-dropdown' to be visible
  44. waitFor(function() {
  45. // Check in the page if a specific element is now visible
  46. return page.evaluate(function() {
  47. return $("#signin-dropdown").is(":visible");
  48. });
  49. }, function() {
  50. console.log("The sign-in dialog should be visible now.");
  51. phantom.exit();
  52. });
  53. }
  54. });