|
|
|
|
|
by ffsm8
257 days ago
|
|
JS is not a realtime language. setTimeout() does not actually guarantee to run after the elapsed time. It merely gets queued for the next async execution window after that timer elapsed. Hence it can also be off by infinity and never get called - because JS is single threaded (unless you use a worker - which comes with its own challenges) and async windows only open if the main thread is "idle". Usually, this is very close to the time you set via setTimeout, but it's very frequently slightly off, too. |
|
Then there are also gotchas like these[0][1]:
> As specified in the HTML standard, browsers will enforce a minimum timeout of 4 milliseconds once a nested call to setTimeout has been scheduled 5 times.
Still, the issue is rather how to measure the elapsed time reliably, for unit-tests among other things.
[0]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setT...
[1]: https://html.spec.whatwg.org/multipage/timers-and-user-promp... (first Note)