将客户端 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 之间,因为服务器时间会设置在时间之间收到请求并准备好响应
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
相关文章