Skip to content

Instantly share code, notes, and snippets.

@rayou
Created June 14, 2015 05:28
Show Gist options
  • Select an option

  • Save rayou/e29f38b894a0a1244e43 to your computer and use it in GitHub Desktop.

Select an option

Save rayou/e29f38b894a0a1244e43 to your computer and use it in GitHub Desktop.
poll
function poll(fn, callback, errback, timeout, interval) {
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
(function p() {
// If the condition is met, we're done!
if(fn()) {
callback();
}
// If the condition isn't met but the timeout hasn't elapsed, go again
else if (Number(new Date()) < endTime) {
setTimeout(p, interval);
}
// Didn't match and too much time, reject!
else {
errback(new Error('timed out for ' + fn + ': ' + arguments));
}
})();
}
// Usage: ensure element is visible
poll(
function() {
return document.getElementById('lightbox').offsetWidth > 0;
},
function() {
// Done, success callback
},
function() {
// Error, failure callback
}
);
//http://davidwalsh.name/essential-javascript-functions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment