Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will setInterval drift?

This is a pretty simple question really. If I use setInterval(something, 1000), can I be completely sure that after, say, 31 days it will have triggered "something" exactly 60*60*24*31 times? Or is there any risk for so called drifting?

like image 448
Deniz Dogan Avatar asked Jun 12 '09 08:06

Deniz Dogan


People also ask

How reliable is setInterval?

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).

Why you should not use setInterval?

In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.

Does setInterval fire right away?

Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set with the required callback.

Does setInterval affect performance?

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.


1 Answers

Short answer: No, you can't be sure. Yes, it can drift.

Long answer: John Resig on the Accuracy of JavaScript Time and How JavaScript Timers Work.

From the second article:

In order to understand how the timers work internally there's one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution.

Both articles (and anything on that site) is great reading, so have at it.

like image 78
Paolo Bergantino Avatar answered Nov 01 '22 17:11

Paolo Bergantino