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 offpoller.init();
more detials: