5

I have an auction site that has a javascript timer counting down. For some reason after 15-20 minutes this timer is lagging the actual time by 20-30 seconds. Over a course of 1 hour the javascript countdown timer can be off by atleast 2-3 minutes. This confuses users as he thinks there are still 2-3 minutes for the auction to close. Once a page loads the server gives the remaining time for the auction which is anything under 2 hours hours & javascript starts counting down from there. So my question is 1) Why is the javascript countdown timer lagging the actual time by a few seconds to minutes after some 20-30 minutes ? 2) how can i ensure the timer is synchronized. I dont want to use ajax to get remaining time as there are many other ajax's running. My server uses Php.

2 Answers 2

10

Your timer is lagging because you are using setTimeout() or setInterval(). They cannot be trusted. Use the Date object instead to get the accurate, current time.

You don't need to synchronize. Just put the auction end time (in UTC) into a date variable, and count down to it.

Sign up to request clarification or add additional context in comments.

3 Comments

Hello Bergi. Can you please share a small code sample of how this can be done ? Appreciate your help.
There's an example in sitepoint.com/creating-accurate-timers-in-javascript. In short: Use Date.now() to calculate the new timeout each time, you know when the next "tick" should happen.
Excellet Bergi. This is exactly what i wanted. Thank you so very much.
1
  1. Javascript time is probably lagging because of many other things that happening in your javascript. A lot depends on your specific timer implementation but Javascript is single threaded so any other operation will delay your timer.

  2. The only way to sync with server is to send a request. You can't eliminate that. But you could send requests only after some number of counts rather than every time. For example, every minute when timer executes it send AJAX request to synchronize. You can find right synchronization period by experimenting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.