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.
13 waitFor = (testFx, onReady, timeOutMillis=3000) ->
14 start = new Date().getTime()
17 if (new Date().getTime() - start < timeOutMillis) and not condition
18 # If not time-out yet and condition not yet fulfilled
19 condition = (if typeof testFx is 'string' then eval testFx else testFx()) #< defensive code
22 # If condition still not fulfilled (timeout but condition is 'false')
23 console.log "'waitFor()' timeout"
26 # Condition fulfilled (timeout and/or condition is 'true')
27 console.log "'waitFor()' finished in #{new Date().getTime() - start}ms."
28 if typeof onReady is 'string' then eval onReady else onReady() #< Do what it's supposed to do once the condition is fulfilled
29 clearInterval interval #< Stop this interval
30 interval = setInterval f, 250 #< repeat check every 250ms
33 page = require('webpage').create()
35 # Open Twitter on 'sencha' profile and, onPageLoad, do...
36 page.open 'http://twitter.com/#!/sencha', (status) ->
37 # Check for page load success
38 if status isnt 'success'
39 console.log 'Unable to access network'
41 # Wait for 'signin-dropdown' to be visible
43 # Check in the page if a specific element is now visible
45 $('#signin-dropdown').is ':visible'
47 console.log 'The sign-in dialog should be visible now.'