Clock initialized by server then run by client is late
I want to create clock that its time initialized by server and then continues with client with this codes:
//initializing by server(ASP.NET):
<% var now=System.DateTime.Now; %>
var h=<%=now.Hour %>;
var m=<%=now.Minute %>;
var s=<%=now.Second %>;
//then client:
function startTime() {
s++;
if (s == 60) {
s = 0;
m++;
if (m == 60) {
m = 0;
h++;
if (h == 24)
h = 0;
}
}
m = checkTime(m);
s = checkTime(s);
h = checkTime(h);
document.getElementById('clock').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () { startTime() }, 1000);
}
function checkTime(i) {
if (i < 10) {
if(i.toString().length<2)
i = "0" + i;
}
return i;
}
window.load = startTime();
but clock become about 5 seconds late for each 10 minute.
How can I prevent this delay?
setTimeout
is not a precise enough to do exact timing. It can easily be off by as much as 10ms
even when nothing else is going on. Over long periods of time this will skew your clock.
An alternative way to implement the clock is to use the native Date
object to do the calculation for you, relying on the system clock, and only use setTimeout
to visually update the time.
Now since setTimeout
can't reliably update the time every second you can set to 100ms
so it will try to update 10 times per second. If your time calculation isn't too heavy this should work nicely.
Check the spec to learn how to use Date
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date (Mozilla Firefox)
改为使用它:
//initializing by server(ASP.NET):
<% var now=System.DateTime.Now; %>
var d=new Date();
var h=<%=now.Hour %>;
var m=<%=now.Minute %>;
var s=<%=now.Second %>;
var sec=d.getSeconds();
//then client:
function startTime() {
var date = new Date();
if (date.getSeconds() != sec) {
sec = date.getSeconds();
s++;
}
if (s == 60) {
s = 0;
m++;
if (m == 60) {
m = 0;
h++;
if (h == 24)
h = 0;
}
}
m = checkTime(m);
s = checkTime(s);
h = checkTime(h);
document.getElementById('clock').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () { startTime() }, 100);
}
function checkTime(i) {
if (i < 10) {
if(i.toString().length<2)
i = "0" + i;
}
return i;
}
window.load = startTime();
链接地址: http://www.djcxy.com/p/86174.html
上一篇: 比较客户端和服务器时间
下一篇: 由服务器初始化并由客户端运行的时钟迟了