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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With