As far as I understand it, setTimeout(code, delay)
will call a callback at the current time plus delay
. Is there a reference clock for when the delay has expired? I.e. if I were to change the computer’s current time, would setTimeout wait a different amount of time?
I’m only asking out of curiosity – not trying to use this. MDN didn’t seem to have the answer.
2
Answers
No it would not be affected by changing computers time, but it is affected by elapsed time.
Moreover – if you setTimeout for lets say 10 seconds and then blur the tab in chrome (or e.g. close mobile Safari), all the operation will halt and the timeout will not be triggered in 10 seconds in the background. However, once the tab is focused (or the the mobile Safari is loaded again). The browser will check and automatically trigger or the timeouts that should have been triggered in the meantime, while it was sleeping.
So that depends…
Firstly, there is no guarantee that your timer will be executed at an exact moment in time. See both whatWG spec and NodeJS Timers docs. JS generally operates in a single thread with a loop in which things occur. If you schedule many things, things will be delayed. Furthermore, this loop can also be paused, as noted by nxtwrld.
Secondly there seem to be no standard that says exactly how to implement this. Timers are added to a global map of active timers and values in that map are "DOMHighResTimeStamp" which might be a Unix timestamp, but doesn’t have to be.
https://w3c.github.io/hr-time/#dom-domhighrestimestamp
So as you can see if the value is a Unix timestamp then checking the timestamp against system clock is a logical thing to do. In which case setTimeout would be affected by system clock changes.
See also: