Skip to content

Instantly share code, notes, and snippets.

@donabrams
Created February 1, 2011 19:26
Show Gist options
  • Save donabrams/806453 to your computer and use it in GitHub Desktop.
Save donabrams/806453 to your computer and use it in GitHub Desktop.
Polling wait for jquery
//
// This polls a function at max $max_attempts until true,
// then executes a function.
// The scope is likely this, but ya never know.
//
// TODO: add failure mechanism
$.pollingWait = function(max_attempts, delay, condFunc, condScope, func, scope /*, arguments */ ) {
var worker = function(attempts, max_attempts, delay, flagFunc, flagScope, func, scope, args) {
if (attempts >= max_attempts) {
return false;
}
if (!flagFunc.apply(flagScope || window, [])) {
//increment attempts
var args2 = [attempts + 1].concat(arguments.slice(1));
//Array.prototype.slice.call(arguments, 1));
var toApply = function() {
worker.apply(this || window, args2 || []);
};
setTimeout(toApply, delay);
}
else {
//apply just the arguments!
func.apply(scope, args);
}
};
worker(0, max_attempts, delay, condFunc, condScope, func, scope, arguments.slice(6));
//Array.prototype.slice.call(arguments, 6));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment