Question

I'm trying to create a countdown timer that's based on a time on the server.

I originally had the server set the time left, and just did a setTimeout for 1 second that would decrement the time.

I found 2 problems with this:

  1. There is a lag from the server setting the time until the client's page is rendered and the JavaScript begins to run. The lag amount depends on the speed of the users internet connection and computer/JavaScript engine.
  2. I think setTimeout of 1 second may have been getting behind a little on slower computers.

I changed it so the server would set the ending time and the JavaScript on the client would take the time (in UTC) and calculate the remaining time left. It would then do this on every setTimeout callback. This makes the time and countdown perfect. If the client has a fast computer/JavaScript engine, the timer stays on page. If the computer/JavaScript engine is slower, you may see a second be skipped here and there, but the time is never off.

I found 1 problem with this method so far:

  1. Every client's clock may be different.

So, the time left may be a couple seconds, or 30 seconds, or even days off if the clients time is not correct on their computer.

Is there a way that I can have the time left be exact based on the server's ending date?

Was it helpful?

Solution

I don't know what kind of resolution you need, but given network and page rendering latencies, it's going to be impossible to get client-server agreement to much better than a second. I would suggest you do an ajax poll every 5 or 10 seconds, and adjust your timer accordingly. There is also comet which is essentially "reverse" ajax, which can push the times to the client. But either way, you still have network and renderign latencies to contend with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top