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