Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 811
smdrager Avatar asked Mar 18 '11 20:03

smdrager


People also ask

How do you make a 10 second timer in JavaScript?

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").


2 Answers

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; 
like image 137
tilleryj Avatar answered Oct 21 '22 05:10

tilleryj


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 
like image 23
David Braun Avatar answered Oct 21 '22 06:10

David Braun