思路很简单,页面Load后 利用ajax读取服务器时间,将该时间作为客户端基准时间,再利用每隔1000ms对时间进行累计,另外,为了减少各方面带来的误差,可定期从服务器读取时间,如下面代码中的checkFlag的判断-600s后重新从服务端获取,当然这里还有网络消耗的时间,无法避免
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> </head> <body> <div id="divTimes"> </div> </body> </html> <script language="javaScript"> <!-- // var clientTime = new Date(); var serverTime = { h: clientTime.getHours(), m: clientTime.getMinutes(), s: clientTime.getSeconds() }; var serverTimeStr = { h: clientTime.getHours().toString(), m: clientTime.getMinutes().toString(), s: clientTime.getSeconds().toString() }; // var checkFlag = 0;//为了减小误差,可以设置该变量,比如当checkFlag到达600时,重新从服务器取得时间 function formatServerTime() { // checkFlag++; if (serverTime.s < 59) {//60s进制 serverTime.s++; } else { serverTime.s = 0; if (serverTime.m < 59) {//60m进制 serverTime.m++; } else { serverTime.m = 0; if (serverTime.h < 23) {//24h进制 serverTime.h++; } else { serverTime.h = 0; } } } if (serverTime.h < 10) serverTimeStr.h = "0" + serverTime.h.toString(); else serverTimeStr.h = serverTime.h.toString(); if (serverTime.m < 10) serverTimeStr.m = "0" + serverTime.m.toString(); else serverTimeStr.m = serverTime.m.toString(); if (serverTime.s < 10) serverTimeStr.s = "0" + serverTime.s.toString(); else serverTimeStr.s = serverTime.s.toString(); $("#divTimes").html(serverTimeStr.h + ":" + serverTimeStr.m + ":" + serverTimeStr.s); // if (checkFlag>600){ // checkFlag=0; // getServerTime(); // return; // } // else window.setTimeout("formatServerTime()", 1000); } function getServerTime() { var myurl = "gst.aspx?rnd=" + Math.random();//该处为获取服务器时间的地址,返回json数据,此处格式为 [{"h":10,"m":25,"s":9}] $.ajax({ type: "post", url: myurl, dataType: "json", success: function (data, textStatus) { if (typeof data[0] == "object") { serverTime = data[0]; formatServerTime(); } }, error: function (e) { } }); } jQuery(document).ready(function () { getServerTime(); }); --> </script>