Is setInterval CPU intensive?

Solution 1:

I don't think setInterval is inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful.

There are ways that you can improve the performance, however, and it's probably wise to do them:

  1. Pass a function to setInterval, rather than a string.
  2. Have as few intervals set as possible.
  3. Make the interval durations as long as possible.
  4. Have the code running each time as short and simple as possible.

Don't optimise prematurely -- don't make life difficult for yourself when there isn't a problem.

One thing, however, that you can do in your particular case is to use the onhashchange event, rather than timeouts, in browsers that support it.

Solution 2:

I would rather say it's quite the opposite. Using setTimeout and setInterval correctly, can drastical reduce the browsers CPU usage. For instance, using setTimeout instead of using a for or while loop will not only reduce the intensity of CPU usage, but will also guarantee that the browser has a chance to update the UI queue more often. So long running processes will not freeze and lockup the user experience.

But in general, using setInterval really like a lot on your site may slow down things. 20 simultaneously running intervals with more or less heavy work will affect the show. And then again.. you really can mess up any part I guess that is not a problem of setInterval.

..and by the way, you don't need to check the hash like that. There are events for that:

onhashchange

will fire when there was a change in the hash.

window.addEventListener('hashchange', function(e) {
    console.log('hash changed, yay!');
}, false);

Solution 3:

No, setInterval is not CPU intensive in and of itself. If you have a lot of intervals running on very short cycles (or a very complex operation running on a moderately long interval), then that can easily become CPU intensive, depending upon exactly what your intervals are doing and how frequently they are doing it.

I wouldn't expect to see any issues with checking the URL every 100 milliseconds on an interval, though personally I would increase the interval to 250 milliseconds, just because I don't expect that the difference between the two would be noticeable to a typical user and because I generally try to use the longest timeout intervals that I think I can get away with, particularly for things that are expected to result in a no-op most of the time.