Loading

A Recursive setTimeout Pattern

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();

more detials:http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/

posted @ 2012-08-01 22:09  .net's  阅读(386)  评论(0)    收藏  举报