做网页时钟,要想时间准确,就从服务器上拉时间数据。
客户机修改本地时间后,有的时钟就不准了,一般情况下不要一直从服务器上拉时间数据,服务器会累。
那么怎么办的?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TrueTime</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
var serTime = new Date(<?php echo time();?> * 1000);
var locTime = new Date();
var deltaTime = locTime - serTime;
var gon = 0;
var gos = 0;
var gonp;
var gol = 400;
function go(){
gon += 1;
let now = new Date();
if (Math.abs(now.getTime() - locTime) >= gol) {
if(Math.floor(Math.abs(now.getTime() - locTime) / gol) == 1){
gos = Math.floor((now.getTime() - (serTime.getTime() + deltaTime)) / gol);
gonp = gon / gos;
locTime = new Date(locTime.getTime() + gol);
}else{
let truetime = Math.floor(gon / gonp * gol + gol/2 ) + serTime.getTime();
locTime = new Date();
deltaTime = locTime.getTime() - truetime;
}
}
window.requestAnimationFrame(go);
}
go();
function getTrueTime(){
return new Date(new Date() - deltaTime);
}
</script>
</head>
<body>
</body>
</html>