Skip to content

Instantly share code, notes, and snippets.

@justinobney
Created October 17, 2012 13:12
Show Gist options
  • Save justinobney/3905459 to your computer and use it in GitHub Desktop.
Save justinobney/3905459 to your computer and use it in GitHub Desktop.
Poll until a condition is met
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