Answer the question
In order to leave comments, you need to log in
How to synchronize time on timer between server and browser using JS?
You need to put a timer on the site with a countdown that should be the same for all users.
I tried to insert the time into the JS code using PHP, but the seconds on the users timer were still different. Is it possible to use JavaScript to make the time for different users the same to the exact second?
Answer the question
In order to leave comments, you need to log in
Probably, it is necessary to write something similar to time synchronization between the client and servers in NTP. This will require several requests to the server in order to estimate the response time - i.e. not immediately from loading the page it will be possible to accurately start the timer. You can show it immediately, and correct it within the next seconds. There is a ready solution: NTPJS , haven't tried it.
In the simplest version, you can get by with one AJAX request after the page has fully loaded. Remember the current local time var tPing = (new Date).getTime();
, request ajax from the server its current time tServ
, get a response and remember the local timetPong
when a response is received. And rely on a very rough hypothesis that the server answered exactly in the middle of the tPing..tPong interval. Those. decide that the difference between server time and local time is exactly tDiff = tServ - tPing + (tPong - tPing) / 2;
Now to get the estimated server "exact" time, just add this tDiff to the current local time.
There are javascript implementations of NTP , usually around 20ms accuracy is achieved.
jehiah.cz/a/ntp-for-javascript
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question