javascript - Clock initialized by server then run by client is late -
i want create clock time initialized server , continues client codes:
//initializing 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) = "0" + i; } return i; } window.load = starttime();
but clock become 5 seconds late each 10 minute.
how can prevent delay?
settimeout
not precise enough exact timing. can off as 10ms
when nothing else going on. on long periods of time skew clock.
an alternative way implement clock use native date
object calculation you, relying on system clock, , use settimeout
visually update time.
now since settimeout
can't reliably update time every second can set 100ms
try update 10 times per second. if time calculation isn't heavy should work nicely.
check spec learn how use date
: https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/date (mozilla firefox)
Comments
Post a Comment