I read somewhere that setInterval is CPU intensive. I created a script that uses setInterval and monitored the CPU usage but didn't notice a change. I want to know if there is something I missed.
What the code does is check for changes to the hash in the URL (content after #) every 100 milliseconds and if it has changed, load a page using AJAX. If it has not changed, nothing happens. Would there be any CPU issues with that.
Yes it is. setTimeout & setInterval are asynchronous. setInterval won't wait until the request is done. It will keep on adding requests to do every second, but it will delay itself if it goes over 1 second.
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
Try doing: setInterval(function () { for (var i = 0; i < 1000; i++) { // YOUR CODE } }, 10); You will actually make your code more efficient by avoiding the callback calling overhead and having longer intervals will make your code run more predictably.
The real-time interval can only be greater than or equal to the value we passed. From the above code, we can see that setInterval is always inaccurate. If time-consuming tasks are added to the code, the difference will become larger and larger ( setTimeout is the same).
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:
setInterval
, rather than a string.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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With