I am building a site which has times and prices which tick down. The thing I am most concerned with is syncing time so that it is as accurate as possible across all clients.
Currently, I am sending the client the number of milliseconds left which is then used to fuel the countdown timer, but due to transfer and rendering delays, this can be off by several seconds even with 2 browsers on the same computer.
Is there a way to sync the client's javascript time and server time, or am I just going to have to deal with this slight lag?
If only there was a way to accurately measure the time difference between the server sending the data and it being received and rendered by the client.
To create a simple 10 second countdown with JavaScript, we use the setInterval method. to add a progress element. let timeleft = 10; const downloadTimer = setInterval(() => { if (timeleft <= 0) { clearInterval(downloadTimer); } document. getElementById("progressBar").
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 milliseconds var endTime = new Date(new Date().getTime() + timeRemaining); // Put this in a setInterval, or however you currently handle it var 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 its instances, 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 the server'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
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