将客户端 javascript 时钟与服务器日期同步的最佳方式 [英] The best way to synchronize client-side javascript clock with server date

查看:27
本文介绍了将客户端 javascript 时钟与服务器日期同步的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项任务是在某个固定时区(MSK 或 MSD - 取决于当前日期)的 HTML 页面上显示数字时钟(具有分钟精度).我想避免依赖客户端系统时钟,因此需要与服务器进行一些同步.HTTP 服务器在每个响应中发送 Date 标头,因此我们可以向我们站点的任何 URL 发送 AJAX GET 或 HEAD 请求以获取服务器日期,计算与客户端日期的差异并在使用 setTimeout() 更新时钟时使用它.还存在其他问题:日光设置的时区切换、连接速度非常慢的延迟.

I have a task to show digital clock (with minutes precision) on HTML page in some fixed timezone (MSK or MSD - depending on current date). I'd like to avoid relying on client system clock, so some synchronization with server is required. HTTP server sends Date header in each response so we can send an AJAX GET or HEAD request to any URL of our site to get server date, calculate the difference with client date and use it when updating clock with setTimeout(). There are other issues remains: timezone switching for daylight settings, latency accounting for very slow connections.

对这个任务有最简单的想法吗?我更愿意在没有服务器端编程的情况下解决它.

Any idea to this task the simpliest way? I'd prefer to solve it without server-side programming.

推荐答案

如果你打算使用 ajax,你应该记住在 readyState==2 和 readyState==3 之间的客户端时间,因为服务器时间将设置在 time on 之间的某个时间收到请求并准备响应

you should remember client time between readyState==2 and readyState==3 if you are going to use ajax, because server time will be set somewhere between time on request recieved and response prepared

这篇关于将客户端 javascript 时钟与服务器日期同步的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆