Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sync javascript countdown timer with server

Tags:

javascript

php

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.

like image 266
Anita Avatar asked Dec 27 '22 01:12

Anita


2 Answers

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.

like image 198
Bergi Avatar answered Dec 29 '22 14:12

Bergi


  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.

like image 34
Alex Gitelman Avatar answered Dec 29 '22 16:12

Alex Gitelman