I need to add a clock to a web page. The clock needs to be synchronized with a server but I really don\'t want to have it constantly check the server as the page will be ope
<script>
var ctoday = <?php echo time() * 1000 ?>;
setInterval(function() {ctoday += 1000;},1000);
function startTime() {
var today = new Date(ctoday);
var montharray = new Array("Jan","Feb","Mar","Abr","May","Jun","Jul","Ogu","Sep","Oct","Nov","Des");
var h = today.getHours();
var ampm = h >= 12 ? 'PM' : 'AM';
h = h % 12;
h = h ? h : 12;
var m = today.getMinutes();
var s = today.getSeconds();
h = checkTime(h);
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
checkTime(today.getDate())+" "+montharray[today.getMonth()]+" "+today.getFullYear() + " (" + ampm +" " + h + ":" + m + ":" + s +")";
setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i};
return i;
}
</script>
<body onLoad="startTime();">
<span id="txt"></span>
</body>
You can get the current time from the server on every page load, so even on first load you will have the current server time. After that, you may use a javascript timer on the page set to tick every second, and then you will virtually have a clock working synchronized with the server. You may also try applying offsets as suggested, but i wouldn't recommend since there's lag during postbacks.
Ajax request might be an interesting option.
Any doubts, you may also check this clock out!
Also, W3Schools is a great reference for javascript.