Colin Snover wrote a good article about why he thinks setInterval is considered harmful:
setInternvalignores errors. If an error occurs in part of your code, it’ll be thrown over and over again.setIntervaldoes 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: