Skip to content

Instantly share code, notes, and snippets.

@kevinweber

kevinweber/poll.js

Last active Sep 2, 2016
Embed
What would you like to do?
Poll function
/**
* Poll function
* based on https://davidwalsh.name/essential-javascript-functions
*/
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();
} else if (Number(new Date()) < endTime) {
setTimeout(p, interval);
} else {
errback(new Error('timed out for ' + fn + ': ' + arguments));
}
}());
}
// Use it like this ...
poll(
function () {
// Condition
return that.value.length;
},
// Success
function () {
// ...
},
// Error
function () {
// ...
},
3000, // Poll timeout
50 // Poll interval
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.