这个方案是在 stackoverflow 看到的一个方案,我们来看看此方案和原方案的区别
原方案
setTimeout系统时间补偿
原理就是:当每一次定时器执行时后,都去获取系统的时间来进行修正,虽然每次运行可能会有误差,但是通过系统时间对每次运行的修复,能够让后面每一次时间都得到一个补偿。
代码如下:
// 定时器
//fun 函数
//speed 间隔时间
function timer(myfun,speed) {
myfun()
var counter = 1,
var start = new Date().getTime();
function instance()
{
myfun()
var ideal = (counter * speed),
real = (new Date().getTime() - start);
counter++;
var diff = (real - ideal);
window.setTimeout(function() { instance(); }, (speed - diff)); // 通过系统时间进行修复
};
window.setTimeout(function() { instance(); }, speed);
}
// 需要定时执行的函数
function printDate(){
console.log(new Date())
}
// 开启定时
timer(printDate,10000)
本文参考:
https://mp.weixin.qq.com/s/QRIXBoKr2dMgLob3Atq9-g
https://stackoverflow.com/questions/196027/is-there-a-more-accurate-way-to-create-a-javascript-timer-than-settimeout