使用服务器时间的 JavaScript 倒计时器
我正在尝试创建一个基于服务器上的时间的倒计时器。
我最初让服务器设置了剩余时间,然后执行了 1 秒的 setTimeout
来减少时间。
我发现了两个问题:
- 服务器设置的时间存在延迟,直到客户端页面呈现并且 JavaScript 开始运行。延迟量取决于用户互联网连接和计算机/JavaScript 引擎的速度。
- 我认为
setTimeout
1 秒可能在速度较慢的计算机上落后了一点。
我更改了它,以便服务器设置结束时间,客户端上的 JavaScript 将获取时间(以 UTC 为单位)并计算剩余时间。然后它会在每个 setTimeout
回调中执行此操作。这使得时间和倒计时变得完美。如果客户端有快速的计算机/JavaScript 引擎,计时器将停留在页面上。如果计算机/JavaScript 引擎较慢,您可能会看到这里或那里跳过了一秒钟,但时间永远不会结束。
到目前为止,我发现此方法有 1 个问题:
- 每个客户端的时钟可能不同。
因此,如果客户计算机上的时间不正确,剩下的时间可能是几秒钟,或 30 秒,甚至几天。
有没有办法让我可以根据服务器的结束日期准确确定剩余时间?
I'm trying to create a countdown timer that's based on a time on the server.
I originally had the server set the time left, and just did a setTimeout
for 1 second that would decrement the time.
I found 2 problems with this:
- There is a lag from the server setting the time until the client's page is rendered and the JavaScript begins to run. The lag amount depends on the speed of the users internet connection and computer/JavaScript engine.
- I think
setTimeout
of 1 second may have been getting behind a little on slower computers.
I changed it so the server would set the ending time and the JavaScript on the client would take the time (in UTC) and calculate the remaining time left. It would then do this on every setTimeout
callback. This makes the time and countdown perfect. If the client has a fast computer/JavaScript engine, the timer stays on page. If the computer/JavaScript engine is slower, you may see a second be skipped here and there, but the time is never off.
I found 1 problem with this method so far:
- Every client's clock may be different.
So, the time left may be a couple seconds, or 30 seconds, or even days off if the clients time is not correct on their computer.
Is there a way that I can have the time left be exact based on the server's ending date?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道您需要什么样的分辨率,但考虑到网络和页面渲染延迟,客户端-服务器协议不可能比一秒好得多。我建议你每 5 或 10 秒进行一次 ajax poll,并相应地调整你的计时器。还有comet本质上是“逆向”ajax,可以推动时代给客户。但无论哪种方式,您仍然需要应对网络和渲染延迟。
I don't know what kind of resolution you need, but given network and page rendering latencies, it's going to be impossible to get client-server agreement to much better than a second. I would suggest you do an ajax poll every 5 or 10 seconds, and adjust your timer accordingly. There is also comet which is essentially "reverse" ajax, which can push the times to the client. But either way, you still have network and renderign latencies to contend with.