Skip to content

Instantly share code, notes, and snippets.

@petermac-
Last active September 12, 2015 19:14
Show Gist options
  • Save petermac-/29d16b1097d57a6518aa to your computer and use it in GitHub Desktop.
Save petermac-/29d16b1097d57a6518aa to your computer and use it in GitHub Desktop.
polling-deferred.js
// The polling function
function poll(fn, timeout, interval) {
var dfd = new Deferred();
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
(function p() {
// If the condition is met, we're done!
if(fn()) {
dfd.resolve();
}
// 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 {
dfd.reject(new Error('timed out for ' + fn + ': ' + arguments));
}
})();
return dfd.promise;
}
// Usage: ensure element is visible
poll(function() {
return document.getElementById('lightbox').offsetWidth > 0;
}, 2000, 150);

With Deferreds: Most JavaScript frameworks/toolkits have a Deferred/Promise implementation so it's implementation would revolve around the Deferred. The code is structured easy enough to read but it's mostly three-fold: the conditional function which signals polling success, a conditional failure which hasn't timeout out, so we'll run again, or a failure which has run past timeout which should return an error.Date.now() vs Number(new Date())

http://davidwalsh.name/javascript-polling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment