Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript setTimeout and changes to system time cause problems

Tags:

I've noticed that if I set the setTimeout for 1 minute in the future, and then change my system time to 5 minutes in the past, the setTimeout function will trigger in 6 minutes.

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

My JavaScript webpage uses a setTimeout function 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?

Edit: I am updating the page using Ajax, I dont want to refresh the entire page.

like image 245
14 revs, 12 users 16% Avatar asked Feb 02 '11 22:02

14 revs, 12 users 16%


People also ask

Does setTimeout affect performance?

No significant effect at all, setTimeout runs in an event loop, it doesn't block or harm execution.

Is JavaScript setTimeout blocking?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute. All other statements that are not part of setTimeout() are blocking which means no other statement will execute before the current statement finishes.

What happens if setTimeout is not cleared?

You don't actually need to use clearTimeout , you only use it if you wish to cancel the timeout you already set before it happens. It's usually more practical to use clearInterval with setInterval because setInterval usually runs indefinitely.

Which event causes delay in JavaScript?

The delay begins at the moment where setTimeout is executed by the JavaScript interpreter, so from the loading of the page if the instruction is in a script executed at load, or from a user action if the script is triggered by it.


1 Answers

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.

like image 93
Siedrix Avatar answered Sep 25 '22 11:09

Siedrix