How to synchronise a client webpage timer with the server How to synchronise a client webpage timer with the server ajax ajax

How to synchronise a client webpage timer with the server


The accepted answer is good and helped inspire me as I wrote a library to solve this problem. The library yields more precise answers by looking at the load times of itself, rather than the whole page (as done with performance.timing above) and then gets even better precision by following with a series of 10 XMLHttpRequests. Also, addressing your second concern, my library doesn't disregard the milliseconds (as does the accepted answer).

The library is called ServerDate and is freely available.

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


In modern browsers, you can achieve this by assigning a timestamp to a JavaScript variable, and use the Performance object to calculate the exact time.

Example:

var tsp = new Date('Sun Feb 19 2012 17:55:14 GMT+0100 (CET)'); // "Timestamp"window.onload = function() {    var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {};    tsp.setTime(tsp.getTime() + performance.timing.loadEventStart - performance.timing.navigationStart    // after window.onload, you're sync with the server    // Example of timer:    setInterval(function() {        tsp.setSeconds(tsp.getSeconds() + 1);        document.title = tsp.toString();    }, 1000); // 1000 ms = timer may be off by 500ms.};

For more information on this object, have a look at the MDN's article.
A demo is provided here.


Ideally your solution would involve the server sending out the signal that the submit form is open to all clients at the same time. For that you could use web sockets if you have no problem with excluding people with older browsers. There are also fallbacks using long polling for those browsers.

I am not sure how well websockets do together with PHP though.

I've only ever used socket.io together with node JS. With that solution it would be trivial to set a server-side timeout and notify all clients at the same time when it's complete. It automatically detects the browser support and chooses a method that works best for a given browser.

Using this solution the clients will only ever allow submissions when the server has told them it is ready. As long as the server you submit to performs validation you should be fine.