我不会在特定时间执行功能(最终目标是在多台计算机上同步媒体播放)。但是,我看到了无法解释的行为。我正在寻找一种解释和一种避免这种情况的方法。
一个相关的问题是How to create an accurate timer in javascript?,但是有些不同。问题是要执行多次,每次执行之间要设置一定的时间差。类似于“每5秒钟执行一次”。我对“在12:05:00执行此操作”感兴趣,即执行一次,但要尽可能接近正确的时间。这样就不能使用上述的漂移调整算法。
让我们从一个测试程序开始,该程序花费当前时间,将时间缩短到几秒钟,然后尝试在未来5秒钟(或更短的时间内)执行一个功能:
<script type="text/javascript">
function boom() {
let timestamp = new Date().getTime();
console.log(" BOOOOOM!!! " + timestamp);
}
function runFunction() {
let currentDate = new Date().getTime();
let nextDate = Math.floor(currentDate / 1000);
nextDate += 5;
nextDate *= 1000;
let diff = nextDate - currentDate;
setTimeout(boom, diff);
console.log("Current time: " + currentDate);
console.log("Next time: " + nextDate);
}
runFunction();
</script>
我的输出是
ontime.html:16 Current time: 1550851837630
ontime.html:17 Next time: 1550851842000
ontime.html:4 BOOOOOM!!! 1550851842591
看起来不错。我错过了591毫秒的目标,这是巨大的,但是如果一直都是这样(看起来确实如此),我可以将其纳入我的计算中:
<script type="text/javascript">
function boom() {
let timestamp = new Date().getTime();
console.log(" BOOOOOM!!! " + timestamp);
}
function runFunction() {
let currentDate = new Date().getTime();
let nextDate = Math.floor(currentDate / 1000);
nextDate += 5;
nextDate *= 1000;
let diff = nextDate - currentDate;
diff -= 591;
setTimeout(boom, diff);
console.log("Current time: " + currentDate);
console.log("Next time: " + nextDate);
}
runFunction();
</script>
我的输出是
ontime.html:16 Current time: 1550852490754
ontime.html:17 Next time: 1550852495000
ontime.html:4 BOOOOOM!!! 1550852494591
591毫秒又错了!这怎么可能?