纯JavaScript实现客户端动态时钟与服务器时间同步

作者:闭包旅人时间:2026-10-24 08:53:58浏览:374

本文介绍如何在.NET环境中利用纯JavaScript在客户端实现动态显示当前时间,避免不必要的Ajax请求。通过封装Timer函数处理时间格式化,并结合GetServerTime函数利用setInterval实现本地时钟每秒更新与定期全页刷新同步服务器时间的机制,兼顾性能与数据准确性。

客户端动态时钟与时间同步方案

过度依赖Ajax并非最佳实践,在客户端直接处理逻辑往往更为高效。


具体实现代码如下:

function Timer(span)
{ 
var tmp = new Date();
var milsecs=Date.parse(tmp.getMonth()+"-"+tmp.getDay()+"-"+tmp.getFullYear()+" "+document.getElementById('lbl_Hour').innerText+":"+document.getElementById('lbl_Minute').innerText+":"+document.getElementById('lbl_Second').innerText);
var timer = new Date(milsecs+span);
var seconds,minutes,hours,date;
if(timer.getSeconds()<10)
seconds = "0"+timer.getSeconds();
else
seconds = timer.getSeconds();
if(timer.getMinutes()<10)
minutes = "0"+timer.getMinutes();
else
minutes = timer.getMinutes();
if(timer.getHours()<10)
hours = "0"+timer.getHours();
else
hours = timer.getHours();
date=timer.getDate();
document.getElementById('lbl_Second').innerText = seconds;
document.getElementById('lbl_Minute').innerText = minutes;
document.getElementById('lbl_Hour').innerText = hours;
} 
该部分逻辑旨在获取服务器时间,并设定每隔updatespan分钟进行一次校验,同时每秒更新一次本地显示时钟。
function GetServerTime(updatespan)
{ 
var clientspan = 1*1000;
//更新本地时钟
setInterval("Timer("+clientspan+")",clientspan);
//同步服务器时钟
setInterval("window.location.href='当前URL'", updatespan);
}
作者最新文章