Created
February 26, 2012 16:47
-
-
Save droot/1917622 to your computer and use it in GitHub Desktop.
Async IF Construct using JQuery Deferred
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
/* 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