Search code examples
javascriptsettimeoutsleep-mode

setTimeout Vs. sleep mode


From what I understood in several SO answers, if a computer goes to sleep mode after a setTimeout has been called, the sleep period should be ignored.

For example:

  • t0: setTimeout(foo, 30000);
  • t0+20s: computer enters sleep mode
  • t0+40s: computer exits sleep mode
  • t0+50s: foo is called

But, my tests shows the following behavior:

  • t0: setTimeout(foo, 30000);
  • t0+20s: computer enters sleep mode
  • t0+40s: computer exits sleep mode and foo is called

My understanding is that when the computer wakes up, if the timeout would have been triggered during the sleep period, it's instantly triggered, otherwise, it's triggered at t0+[timeout value].

So what's the expected behavior? Is it the same across all browsers and OS?

One of my tests (with the latest version of Chrome on Windows 10): https://codepen.io/robloche/pen/GRJvEJB


Solution

  • To sum up the comments above:

    • The behavior I describe seems to make sense for everyone.
    • I'm still not sure that meets the specs or that all browsers implement it this way.

    My initial problem being the renewal of an authentication token, I ended up with a solution that doesn't use setTimeout (thanks to https://stackoverflow.com/a/6347336/603393):

    • When I get a token, I compute and store the next renewal date
    • I use setInterval to regularly check next renewal date is in the past.

    This way, it doesn't matter if the computer wakes up 1 second before the next renewal date or 36 hours after.