Created
December 3, 2012 13:51
-
-
Save jasonhwest/4195171 to your computer and use it in GitHub Desktop.
JavaScript: Recursive setTimeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//original from http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/ | |
var poller = { | |
// number of failed requests | |
failed: 0, | |
// number of failed requests allowed | |
failedLimit: 10, | |
// starting interval - 5 seconds | |
interval: 5000, | |
// kicks off the setTimeout | |
init: function(opts){ | |
if (typeof opts === "object") { | |
if (typeof opts.failedLimit === "number") { this.failedLimit = opts.failedLimit; } | |
if (typeof opts.interval === "number") { this.interval = opts.interval; } | |
} | |
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 < this.failedLimit ){ | |
// give the server some breathing room by | |
// increasing the interval | |
this.interval += 1000; | |
// recurse | |
this.init(); | |
} | |
} | |
}; | |
// kick this thing off | |
poller.init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment