Skip to content

Instantly share code, notes, and snippets.

@droot
Created February 26, 2012 16:47
Show Gist options
  • Save droot/1917622 to your computer and use it in GitHub Desktop.
Save droot/1917622 to your computer and use it in GitHub Desktop.
Async IF Construct using JQuery Deferred
/* asynchronous IF construct implementation */
async_if = function(fn, args, timeout) {
var curr_probe, dfd, probe;
dfd = new jQuery.Deferred();
curr_probe = null;
probe = function() {
if (fn(args)) {
dfd.resolve(args); /* this will invoke success callback */
return curr_probe = null;
} else {
/* lets return after 5 milliseconds to re-run checker function */
return curr_probe = setTimeout(probe, 5);
}
};
if (timeout) {
/* if this is timeout async operation, return failure if condition is not met within timeout */
setTimeout(function() {
curr_probe && clearTimeout(curr_probe);
return dfd.reject(args);
}, timeout);
}
probe();
return dfd.promise();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment