← all posts

A Recursive setTimeout Pattern

Monday, October 18, 2010

Colin Snover wrote a good article about why he thinks setInterval is considered harmful:

  1. setInterval ignores errors. If an error occurs in part of your code, it'll be thrown over and over again.
  2. 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:

  1. Declaring a function loopsiloop that is immediately invoked (notice the parens at the end).
  2. Declaring a timeout handler to fire after 5 seconds.
  3. 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.

comments powered by Disqus