使用服务器和系统时间在网页上显示时钟?
我需要向网页添加时钟。时钟需要与服务器同步,但我真的不想让它不断检查服务器,因为页面将在多台 PC 上 24/7 打开。有没有什么方法可以从服务器获取时间,然后使用系统时钟来保持更新,并每 15 分钟左右检查一次服务器以保持同步?
I need to add a clock to a web page. The clock needs to be synchronized with a server but I really don't want to have it constantly check the server as the page will be open 24/7 on several PCs. Is there some way to get the time from the server and then use the systems clock to keep it updated and check the server every 15 minutes or so to keep it synced?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我之前处理这个问题的方法是:
您只需偶尔从服务器更新即可。
但您必须解决的问题是,在发出从服务器获取时间的请求时,在获取客户端时间之前会出现延迟。您可以通过使用 ajax 请求来获取服务器时间而不是其他任何东西来最大限度地减少这种情况,从而减少开销和网络延迟等。
The way I've gone about this before is:
You only need to update this occasionally from the server.
The problem that you've got to sort out though is that in making a request to get the time from the server, there will be a lag before you can get the client time. You can probably minimize this by using an ajax request to get the server time and nothing else, thereby cutting overhead and network lag etc.
+Date.now()
返回自 Unix 纪元以来的本地毫秒数。因此:或者类似的东西。
这是一个演示前半部分的小提琴:
+Date.now()
returns local ms since the Unix epoch. So:Or something like that.
Here's a fiddle demonstrating the first half:
一种想法是在请求时响应页面上的日期时间。
像:
**注意:这只是想法,代码可能无法工作
one idea is to response datetime on page when it is requested.
like:
**note : this is idea only, code may not work
您可以在每次页面加载时从服务器获取当前时间,因此即使在第一次加载时您也将获得当前服务器时间。
之后,您可以在页面上使用 javascript 计时器,将其设置为每秒滴答一次,然后您实际上将拥有一个与服务器同步工作的时钟。您也可以尝试按照建议应用偏移量,但我不建议这样做,因为回发期间会出现延迟。
Ajax 请求可能是一个有趣的选择。
如有疑问,您还可以查看这个时钟!
另外,W3Schools 是 JavaScript 的一个很好的参考。
You can get the current time from the server on every page load, so even on first load you will have the current server time.
After that, you may use a javascript timer on the page set to tick every second, and then you will virtually have a clock working synchronized with the server. You may also try applying offsets as suggested, but i wouldn't recommend since there's lag during postbacks.
Ajax request might be an interesting option.
Any doubts, you may also check this clock out!
Also, W3Schools is a great reference for javascript.
ID为“txt”的
with ID "txt"
尝试下面的代码:
Try below code this :
您只需从服务器获取一次日期时间,加载时调用此方法并使用 Moments js 来格式化日期:
you just get one time date time from server, on load call this method and use moments js for format date: