How to sync a javascript countdown with server time [duplicate] How to sync a javascript countdown with server time [duplicate] javascript javascript

How to sync a javascript countdown with server time [duplicate]


Even though the time on the server and client is going to be different, the rate at which time changes should essentially be same. I would send the remaining time down to the client, let the client then add that time to the current time, and then have the client calculate the countdown from that. For example:

var timeRemaining = [rendered on page load or queried by ajax]; // in millisecondsvar endTime = new Date(new Date().getTime() + timeRemaining);// Put this in a setInterval, or however you currently handle itvar countdown = (endTime.getTime() - new Date().getTime()) / 1000;


There is a way to synchronize a client with the server's time. I wrote a library that does just this: ServerDate.

Here's part of the README:

You can use ServerDate as you would use the Date function or one of itsinstances, e.g.:

> ServerDate()"Mon Aug 13 2012 20:26:34 GMT-0300 (ART)"> ServerDate.now()1344900478753> ServerDate.getMilliseconds()22

There is also a new method to get the precision of ServerDate's estimate of theserver's clock (in milliseconds):

> ServerDate.toLocaleString() + " ± " + ServerDate.getPrecision() + " ms""Tue Aug 14 01:01:49 2012 ± 108 ms"

You can see the difference between the server's clock and the browsers clock, in milliseconds:

> ServerDate - new Date()39


You can measure the time the full server roundtrip takes and divide by two to get a good estimate for the time difference. Be careful: it's not guaranteed that IP packages take the same route in both directions, but the propability is quite high.

You can use Date.getTime() if millisesonds resolution is enough for you.