
[英]Using while(Date.now() < interval) {} with requestAnimationFrame()
[英]Inconsistent delta when using requestAnimationFrame and Date.now()
我有一个简单的片段:
let startTime = -1
let lastNow = -1
let lastTS = -1
const animate = (timeStamp)=>{
requestAnimationFrame(animate)
const now = Date.now()
if(lastTS===-1){
lastTS = timeStamp
lastDate = now
}
const deltaTS = timeStamp - lastTS
lastTS = timeStamp
const deltaNow = now - lastNow
lastNow = now
console.log(deltaTS,deltaNow)
}
animate(-1)
我看到了我的期望,这些值有些相似, timestamp
更加精确
但是,当在庞大的代码库中使用这个确切的代码时,我看到了非常不一致的结果。 从 raf 的时间戳派生的增量与我的刷新率一致,比较两个Date.now()
调用的增量在 4 到很多之间变化。 可能是什么原因造成的? 我怀疑我可能有animate(-)
触发了几次,但我仍然不明白为什么这些会如此奇怪地间隔开。
传递给requestAnimationFrame
回调的时间戳,在 Chrome 中至少是 Firefox,是最后一个 V-Sync 信号的时间,在规范中是渲染帧开始的时间。
同一渲染帧中的所有回调将共享相同的时间戳。
所以你在这里看到的可能只是你自己的回调在一些重的回调之后触发:
requestAnimationFrame((ts) => { const now = performance.now(); const diff = now - ts; console.log("first callback", { ts, now, diff }); while(performance.now() - now < 200) { // block the event-loop 200ms } }); requestAnimationFrame((ts) => { const now = performance.now(); const diff = now - ts; console.log("second callback", { ts, now, diff }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.