setInterval is Bad

I got another reminder today of how bad setInterval can be. You just don’t hear┬ádevelopers talking about the problems with setInterval. In fact, I’ve seen numerous tutorials where good developers are using it in their examples. We need to start addressing this and start talking about the problems with setInterval.

What happens when your function fails?

Let’s take a look at the following piece of code:


setInterval(function() {
  $.get('/api/posts', function(data) {
    console.log(data);
  });
}, 1000);

This code snippet is pretty simple. It does an GET request to an API point, looking to retrieve all posts and dump the data to the console. What would happen if there was an error on the API server? Would our loop stop doing the request? No, it would keep executing over and over, even if our AJAX call was being held up. This could hold up our whole server and create big performance problems for us.

There is a better way! Let’s use setInterval’s little cousin setTimeout. We can use setTimeout to get the functionality we want, with our little friend recursion.


(function doApiCall() {
  $.get('/api/posts', function(data) {
    console.log(data);
  });
  setTimeout('doApiCall', 1000);
})();

When our function runs into a problem, it is not called again until the function finishes execution. No more server hangups.

Comments

  1. Hmm… can’t you call clearTimeout if there’s an error in the setTimeout method?

    So something like this:

    var pollingFunc = setInterval(function() {
    $.get(‘/api/posts’, function(data) {
    console.log(data);
    }, function() {
    console.log(‘Failure handler. Bailing…’);
    clearInterval(pollingFunc);
    });
    }, 1000);

Leave a Reply

Your email address will not be published. Required fields are marked *