skip to Main Content

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


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

    Login or Signup to reply.
  2. 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

    The DOMHighResTimeStamp type is used to store a duration in milliseconds. Depending on its context, it may represent the moment that is this duration after a base moment like a time origin or the Unix epoch.

    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:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search