如何实现精准的setTimeout
setTimeout 是不准的。因为 setTimeout 是一个宏任务,它的指定时间指的是:进入主线程的时间。
setTimeout(callback, 进入主线程的时间)
所以什么时候可以执行 callback,需要看 主线程前面还有多少任务待执行。
function timer(speed) {
counter = 1,
start = new Date().getTime();
window.setTimeout(function() { instance(speed,counter,start); },speed);
}
function instance (speed,counter,start) {
//其他自己的逻辑 自己写上去
var real = (counter * speed), //真实执行时间
ideal = (new Date().getTime() - start); //系统执行时间
var diff = (ideal - real);//真实执行时间差距
counter++; //执行次数
window.setTimeout(function() { instance(speed,counter,start); },(speed - diff)); // 通过系统时间进行修复 ,第二次执行时间变成了执行时间减去误差时间,等于执行时间间隔缩短了。修正了之前的误差
};
timer(1000);