如何将客户端网页计时器与服务器同步

Flu*_*ten 4 javascript ajax time synchronization client-side

将网页上的时间与服务器同步的最佳方法是什么?

我的网页需要同时为所有用户开始倒计时,并在完全相同的时间结束,以防止任何一个用户有轻微的时间优势.

我的问题类似于这个问题,但接受的答案有帮助,但没有完全回答我的担忧: 如何同步-javascript-countdown-with-server-time

我在pageload之后使用Ajax来获取服务器时间,但我保证在15分钟内倒计时将在每个客户端完全相同的时间结束吗?

即使定时器准确地测量时间,由于忽略setInterval的毫秒数而导致客户端页面之间仍然存在不到1秒的差异 - 有没有办法克服这个问题?

Dav*_*aun 9

接受的答案是好的,并帮助激励我,因为我写了一个库来解决这个问题.通过查看自身的加载时间而不是整个页面(与上面的performance.timing一样),库可以产生更精确的答案,然后通过一系列10个XMLHttpRequests获得更好的精度.此外,解决您的第二个问题,我的库不会忽略毫秒(如接受的答案).

该库名为ServerDate,可免费使用.

这是自述文件的一部分:

您可以ServerDate像使用Date函数或其中一个实例一样使用,例如:

> ServerDate()
"Mon Aug 13 2012 20:26:34 GMT-0300 (ART)"

> ServerDate.now()
1344900478753

> ServerDate.getMilliseconds()
22
Run Code Online (Sandbox Code Playgroud)

还有一种新方法可以获得ServerDate估计服务器时钟的精度(以毫秒为单位):

> ServerDate.toLocaleString() + " ± " + ServerDate.getPrecision() + " ms"
"Tue Aug 14 01:01:49 2012 ± 108 ms"
Run Code Online (Sandbox Code Playgroud)

您可以看到服务器的时钟和浏览器时钟之间的差异,以毫秒为单位:

> ServerDate - new Date()
39
Run Code Online (Sandbox Code Playgroud)


Rob*_*b W 5

在现代浏览器中,您可以通过为 JavaScript 变量分配时间戳来实现这一点,并使用该Performance对象计算准确时间。

例子:

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.
};
Run Code Online (Sandbox Code Playgroud)

有关此对象的更多信息,请查看MDN 的文章这里
提供一个演示。