Tiny little JavaScript polling object
Few days I came across this situation where I had to check, at predefined interval, against a remote server for some conditions. So just for not having the setTimeout and setInterval ids hanging around my code, I wrapped everything in a small JavaScript object Poller.
It's pretty simple: just configure any number of intervals, a callback in case of success, a callback in case of failure, and the function that checks the server
var poller = new Poller();
poller.intervals([1000,5000,10000])
.checkback(function(callback) {
// could be anything asynchronous
$.getJSON('/is/server/ready', function(response) {
if (response.ready) {
callback(true);
} else {
callback(false);
}
})
.callback(function() {
// checkback succeded and the end of one interval
// stops the poller and callback
console.log('Ok')
})
.failback(function() {
// after the third attempt, exits calling the failback
console.log('Failed');
})
.start(); // start the process
Each callback(), failback(), checkback() run in the Poller context, means that this operator points to the Poller instance.
A bunch of additional methods are available like: start(), stop(), restart(), next().
To do: implement Deferred pattern for the method that checks the server
Update: Update with a GitHub repository and support for deferred/promise.