Search code examples
javascriptsettimeoutsystem-clock

JavaScript timer (setTimeout) not affected by system time changes


I've noticed that if I call the JavaScript setTimeout() function with a 1 minute delay, and then change my system time to 5 minutes in the past, the callback function will trigger in 6 minutes.

I did this because I wanted to see what happens during a daylight savings change to the system clock.

My webpage calls setTimeout() to automatically refresh the page every 5 seconds, and if daylight savings were to occur, then the page information would freeze for an hour. Is there a workaround which respects the delay even when such rare changes to the clock occur?

I am updating the page using Ajax, I don't want to refresh the entire page.


Solution

  • What I will do is change from opening a new Ajax request every 5 seconds to using Comet (long polling). It is a better option because the server will push the new results to the browser every time that they are needed, this can be every 5 seconds on server side or every time new information is available.

    Even better would be to use web sockets and have Comet as fall back. This is easy to implement with Faye or socket.io.

    There are other options, like CometD or Ape.