1 原生setTimeout实现
?
// 原生setTimeout执行
let form ={}
function timer() {
var speed = 50, // 设定间隔
counter = 1, // 计数
start = new Date().getTime();
function instance()
{
var ideal = (counter * speed),
real = (new Date().getTime() - start);
var diff = (real - ideal);
counter++;
form.ideal = ideal; // 记录理想值
form.real = real; // 记录真实值
form.diff = diff; // 差值
console.log(form)
if(form.ideal < 2583){
window.setTimeout(function() { instance(); }, speed);
}
};
window.setTimeout(function() { instance(); }, speed);
}
// 启动原生setTimeout测试
timer();
?
结果:相差时间越来越长
2??requestAnimationFrame 方式实现,根据浏览器的刷新频率1s 60次
// requestAnimationFrame
function animationFrame () {
let startTime = Date.now()
var speed = 17 // 设定间隔
var counter = 0 // 计数
var start = new Date().getTime();
function loop () {
const now = Date.now()
var ideal = (counter * speed)
var real = (new Date().getTime() - start);
var diff = (real - ideal);
counter++
form.ideal = ideal; // 记录理想值
form.real = real; // 记录真实值
form.diff = diff; // 差值
console.log(form)
if(now - startTime < 2000) {
requestAnimationFrame(loop)
}
}
loop()
}
animationFrame()
结果:时间比较准 但是不能调整 越16 17 ms执行一次
3 setTimeout 通过系统时间补偿实现
// 系统时间补偿
function timercom() {
var speed = 50,
counter = 1,
start = new Date().getTime();
function instance() {
var real = (counter * speed),
ideal = (new Date().getTime() - start);
var diff = (ideal - real);
counter++;
form.ideal = ideal; // 记录理想值
form.real = real; // 记录真实值
form.diff = diff; // 差值
console.log(form)
if(form.ideal < 3500){
window.setTimeout(function() { instance(); }, (speed - diff)); // 通过系统时间进行修复
}
};
window.setTimeout(function() { instance(); }, speed);
}
// 启动系统时间补偿测试
timercom()
结果:时间可以设定 相差结果很小