问题描述
我正在建立一个有时间和价格下降的网站。我最关心的是同步时间,以便在所有客户端之间尽可能准确。
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.
目前,我向客户端发送剩余的毫秒数然后用于为倒数计时器提供燃料,但是由于传输和渲染延迟,即使在同一台计算机上有2个浏览器,也可能会关闭几秒钟。
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.
有没有办法同步客户端的javascript时间和服务器时间,或者我只是要处理这种轻微的延迟?
如果只是有一种方法可以准确地测量发送数据的服务器与客户端接收和呈现数据之间的时差。
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.
推荐答案
即使服务器和客户端上的时间不同,时间变化的速率也应基本相同。我会将剩余时间发送到客户端,然后让客户端将该时间添加到当前时间,然后让客户端计算倒计时。例如:
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;
这篇关于如何将javascript倒计时与服务器时间同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!