您的脚本的作用是轮询服务器上 inc/clock.php 上的脚本,并(大约)每秒用脚本的输出替换 #clock_time 元素的内容。
如果您有一个 id 为clock_element 的元素和位于 yoursite.tld/inc/clock.php 的脚本,这应该可以工作
但是,我不同意不断轮询服务器的当前时间。只需将时间同步到您的网络服务器一次就足够了。除了一些细微的差异之外,这应该可以让您的时钟在一段时间内保持良好的同步。如果您的网络应用程序运行时间超过几个小时或几天,您应该定期重新同步时钟(每天或每周一次即可)。
使用 Date 对象来跟踪客户端上的服务器时间。只需从clock.php的输出创建一个Date对象(作为先决条件的有效日期输出),并根据您将时钟与远程服务器同步的时间增量定期(例如每秒)更新您的clock_element。
这里有一些粗略的代码,未经测试,可能有一些语法错误,但简要说明了你应该做什么:
function setupServerClock( clock_element, remote_time_url, remote_update_interval, local_update_interval ) {
var w = window;
// client time on resync
var ct = new Date();
// server time on resync
var st = new Date();
// setup resync
w.setInterval( function() {
jQuery.ajax( {
url: remote_time_url,
success: function (data) {
ct = new Date();
st = new Date(data);
}
});
}, remote_update_interval);
// setup local clock display
w.setInterval( function() {
// the time passed on our local machine since the last resync
var delta = new Date() - ct;
// we assume the same time passed at the server
// (yeah, I know, spacetime might not be the same at the servers
// place and off the shelve clocks are pretty inaccurate)
var clock = st - 0 + delta; // - 0 to convert to microsecond timestamp
jQuery(clock_element).html(new Date(clock));
}, local_update_interval);
}
用类似的方式调用它:
setupServerClock( jQuery('#clock_element'), 'inc/clock.php', 1000 * 60 * 60, 1000 );
这将使用从 yourdomain.tld/inc/clock.php 返回的值将时钟设置为写入#clock_element,每小时重新同步时钟并每秒更新时钟的本地表示。
哦,如果定期重新同步确实会导致时钟“跳跃”,您可以考虑简单地向用户提供反馈,表明他的时钟已更新,例如像这样
w.setInterval( function() {
jQuery(clock_element).html('resyncing clock...');
jQuery.ajax( {
url: remote_time_url,
success: function (data) {
ct = new Date();
st = new Date(data);
}
});
}, remote_update_interval);