Created
October 17, 2012 13:12
-
-
Save justinobney/3905459 to your computer and use it in GitHub Desktop.
Poll until a condition is met
This file contains hidden or 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
function when_condition_met(fn_condition, fn_callback, interval, opt_max_attempt) { | |
var poll_id; | |
var run_count = 0; | |
poll_id = setInterval(function () { | |
if (typeof opt_max_attempt == "number" && run_count == opt_max_attempt) { | |
clearInterval(poll_id); | |
return; // possible run onfail callback.. If so refactor to be onject based params. | |
} | |
if (fn_condition()) { | |
clearInterval(poll_id); | |
fn_callback(); | |
} | |
run_count++; | |
}, interval); | |
} | |
/* =========== USAGE =========== | |
var notnull = null; | |
setTimeout(function(){ | |
notnull = { | |
label: 'Some Value', | |
value: 54 | |
}; | |
}, 3500); | |
var _condition = function () { | |
console.log('testing...'); | |
return notnull !== null; | |
}; | |
var _callback = function(){ | |
alert('Condition was met'); | |
}; | |
var _interval = 500; | |
when_condition_met(_condition, _callback, _interval, 4); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment