Created
March 29, 2012 15:01
-
-
Save granteagon/2238248 to your computer and use it in GitHub Desktop.
Wait until a function returns true, then execute a callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Author: Grant Eagon | |
Function: Runs a function every number of milliseconds you specify and executes | |
a callback function when that function returns true. | |
Note: The reason for using a function instead of testing a variable is to | |
avoid using the eval() function. | |
Note 2: It's a good idea to nest your waitUntil function call inside another | |
function, since practical uses of waitUntil typically will need to test one or | |
more global variables. | |
Example usage: The follow set of functions uses waitUntil() to check to see | |
if 5 seconds have passed. | |
function getSecond() { | |
var date = new Date; | |
return date.getSeconds(); | |
} | |
(function alertAfter5Seconds() { | |
"use strict"; | |
var startSeconds = getSecond(); | |
waitUntil(function () { | |
return (getSecond() >= startSeconds + 5) ? true : false; | |
}, function () { | |
alert('5 seconds have passed!'); | |
}, 1000); | |
}()); | |
*/ | |
// run boolFn every [delay] miliseconds, until it returns true, then callback() | |
function waitUntil(boolFn, callback, delay) { | |
"use strict"; | |
// if delay is undefined or is not an integer | |
delay = (typeof (delay) === 'undefined' || isNaN(parseInt(delay, 10))) ? 100 : delay; | |
setTimeout(function () { | |
(boolFn()) ? callback() : waitUntil(boolFn, callback, delay); | |
}, delay); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote it this way to avoid using eval. Haven't figured out how to get around that yet. I would prefer to just pass in a statement. The problem is that (unless you use eval), javascript won't check the variables in the statement for new values. It just takes the initial variable values passed to the function call.