A Recursive setTimeout Pattern
Colin Snover wrote a good article about why he thinks setInterval
is considered harmful:
setInternval
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:
// old and busted - don't do this setInterval(function(){ $.ajax({ url: 'foo.htm', success: function( response ){ // do something with the response } }); }, 5000); // new hotness (function loopsiloop(){ setTimeout(function(){ $.ajax({ url: 'foo.htm', success: function( response ){ // do something with the response loopsiloop(); // recurse }, error: function(){ // do some error handling. you // should probably adjust the timeout // here. loopsiloop(); // recurse, if you'd like. } }); }, 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:
// keep track of how many requests failed var failed = 0; (function loopsiloop( interval ){ interval = interval || 5000; // default polling to 1 second setTimeout(function(){ $.ajax({ url: 'foo.htm', success: function( response ){ // do something with the response loopsiloop(); // recurse }, error: function(){ // only recurse while there's less than 10 failed requests. // otherwise the server might be down or is experiencing issues. if( ++failed < 10 ){ // give the server some breathing room by // increasing the interval 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:
// keep track of how many requests failed var failed = 0, interval = 5000; function errorHandler(){ if( ++failed < 10 ){ // give the server some breathing room by // increasing the interval interval = interval + 5000; loopsiloop( interval ); } } (function loopsiloop( interval ){ setTimeout(function(){ $.ajax({ url: 'foo.htm', success: function( response ){ // what you consider valid is totally up to you 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 = { // number of failed requests failed: 0, // starting interval - 5 seconds interval: 5000, // kicks off the setTimeout init: function(){ setTimeout( $.proxy(this.getData, this), // ensures 'this' is the poller obj inside getData, not the window object this.interval ); }, // get AJAX data + respond to it getData: function(){ var self = this; $.ajax({ url: 'foo.htm', success: function( response ){ // what you consider valid is totally up to you if( response === "failure" ){ self.errorHandler(); } else { // recurse on success self.init(); } }, // 'this' inside the handler won't be this poller object // unless we proxy it. you could also set the 'context' // property of $.ajax. error: $.proxy(self.errorHandler, self) }); }, // handle errors errorHandler: function(){ if( ++this.failed < 10 ){ // give the server some breathing room by // increasing the interval this.interval += 1000; // recurse this.init(); } } }; // kick this thing off poller.init();
And there you have it – a safe, basic, and organized AJAX poller to get you started.
Related posts:
- Using Deferreds in jQuery 1.5
- A New And Improved jQuery Idle Timeout Plugin
Tags: javascript, jQuery, polling
Using
$.widget.bridge
Outside of the Widget Factory Using Deferreds in jQuery 1.5
Nice pattern, could probably add a time difference aspect to make sure that requests still go out every 5sec as long as the response is received within that time. Thanks for posting.
Very nice article and exactly what I was looking for. The object at the end is particularly nice.
Interesting. Is there a potential memory problem here, though? I mean, if the last step of foo() is to call bar(), then foo() isn’t complete until bar() is complete, right? If foo() calls itself recursively every X milliseconds forever, won’t the stack grow indefinitely while the page is loaded?
No, there is not a memory problem. setTimeout place on some event queue a function to be run later, then returns immediately. There is no stack frame waiting around for that function to complete.
Is there a way to make the poller instance based so that I can init multiple pollers doing different things?
jQuery already has builtin .delay(ms) isn’t that doing the same?
Does someone know how this deals with errors?
Great Post! I will implement this on my next project. But: Can you call this a “pattern” ?
This helps. I was wondering about this too.
Very helpful post. Thanks .