使用服务器时间的 JavaScript 倒计时器

发布于 2024-10-08 12:39:40 字数 634 浏览 3 评论 0原文

我正在尝试创建一个基于服务器上的时间的倒计时器。

我最初让服务器设置了剩余时间,然后执行了 1 秒的 setTimeout 来减少时间。

我发现了两个问题:

  1. 服务器设置的时间存在延迟,直到客户端页面呈现并且 JavaScript 开始运行。延迟量取决于用户互联网连接和计算机/JavaScript 引擎的速度。
  2. 我认为 setTimeout 1 秒可能在速度较慢的计算机上落后了一点。

我更改了它,以便服务器设置结束时间,客户端上的 JavaScript 将获取时间(以 UTC 为单位)并计算剩余时间。然后它会在每个 setTimeout 回调中执行此操作。这使得时间和倒计时变得完美。如果客户端有快速的计算机/JavaScript 引擎,计时器将停留在页面上。如果计算机/JavaScript 引擎较慢,您可能会看到这里或那里跳过了一秒钟,但时间永远不会结束。

到目前为止,我发现此方法有 1 个问题:

  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:

  1. 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.
  2. 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:

  1. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阿楠 2024-10-15 12:39:40

我不知道您需要什么样的分辨率,但考虑到网络和页面渲染延迟,客户端-服务器协议不可能比一秒好得多。我建议你每 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文