Skip to content

Instantly share code, notes, and snippets.

@petermac-
Last active September 12, 2015 19:14
Show Gist options
  • Save petermac-/8fc9ed341308354800a3 to your computer and use it in GitHub Desktop.
Save petermac-/8fc9ed341308354800a3 to your computer and use it in GitHub Desktop.
polling.js
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
}
);

If you aren't using Deferreds, no worry -- polling is just about the same. The difference here is that there's no return value -- the callback functions take the place of the Deferred instance.Polling isn't necessarily a consequence of async coding but it has definitely increased in usage and importance due to our desire to write async code. During my time writing front-end functional tests with the Intern testing framework, I've used polling quite a bit both on the server and client sides. This technique will always have its place so make sure you have a snippet like this available.

http://davidwalsh.name/javascript-polling

Andrea Giammarchi I would return {cancel: function () { clearTimeout(interval); }} to the non deferred option in order to provide superior control to the poller author.

David Walsh That’s a great idea!

Date.now() vs Number(new Date())

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