Colin Snover wrote a good article about why he thinks setInterval
is considered harmful:
setInterval
ignores errors. If an error occurs in part of your code, it'll be thrown over and over again.setInterval
does not care about network latency. When continuously polling a remote server for new data, the response could take longer than the interval amount, resulting in a bunch of queued up AJAX calls and an out-of-order DOM.
The solution is to recursively call a named function within setTimeout
, which guarantees that your logic has completed before attempting to call it again. At such, this also doesn't guarantee that your logic will occur on a regular interval. If you want new data every 10 seconds and it takes 15 for your response to come back, you're now behind by 5 seconds. Colin notes that you can adjust your delay if need be, but you shouldn't really care as JavaScript timers are not accurate to begin with.
So how to do this? Consider an AJAX poller as this is a common use case:
setInterval(function(){
$.ajax({
url: 'foo.htm',
success: function( response ){
}
});
}, 5000);
(function loopsiloop(){
setTimeout(function(){
$.ajax({
url: 'foo.htm',
success: function( response ){
loopsiloop();
},
error: function(){
loopsiloop();
}
});
}, 5000);
})();
I'm doing three things here:
- Declaring a function
loopsiloop
that is immediately invoked (notice the parens at the end). - Declaring a timeout handler to fire after 5 seconds.
- Polling the server inside the timeout, which upon either success/failure will call
loopsiloop
and continue the poll.
It's also important to remember that DOM manipulation takes time as well. With this pattern we're guaranteed that the response will be back from the server AND the DOM will be loaded with new content before attempting to request more data.
It's wise to add error handling in cases when the server experiences latency issues or becomes unresponsive. When requests fail, try increasing the polling interval to give the server some breathing room, and only recurse when under a fixed amount of failed attempts:
var failed = 0;
(function loopsiloop( interval ){
interval = interval || 5000;
setTimeout(function(){
$.ajax({
url: 'foo.htm',
success: function( response ){
loopsiloop();
},
error: function(){
if( ++failed < 10 ){
interval = interval + 1000;
loopsiloop( interval );
}
}
});
}, interval);
})();
But the success handler can still fire even if the response is an error, the astute reader might say. For that, let's break out the error logic from its handler so it can also be used in the success callback:
var failed = 0, interval = 5000;
function errorHandler(){
if( ++failed < 10 ){
interval = interval + 5000;
loopsiloop( interval );
}
}
(function loopsiloop( interval ){
setTimeout(function(){
$.ajax({
url: 'foo.htm',
success: function( response ){
if( response === "failure" ){
errorHandler();
}
},
error: errorHandler
});
}, interval);
})();
Good, except that now we have a bunch of floating variables and functions. Ugly, amirate? Let's organize this into an object literal:
var poller = {
failed: 0,
interval: 5000,
init: function(){
setTimeout(
$.proxy(this.getData, this),
this.interval
);
},
getData: function(){
var self = this;
$.ajax({
url: 'foo.htm',
success: function( response ){
if( response === "failure" ){
self.errorHandler();
} else {
self.init();
}
},
error: $.proxy(self.errorHandler, self)
});
},
errorHandler: function(){
if( ++this.failed < 10 ){
this.interval += 1000;
this.init();
}
}
};
poller.init();
And there you have it – a safe, basic, and organized AJAX poller to get you started.