gpt4 book ai didi

javascript - requestAnimationFrame 回调中的参数到底是什么?

转载 作者:行者123 更新时间:2023-11-29 10:59:22 33 4
gpt4 key购买 nike

只需运行这个:

function requestAndDraw() {
requestAnimationFrame((t) => {
console.log(`T: ${t} P.now:${performance.now()}`);
});
}

intId = setInterval(requestAndDraw, 20);
setTimeout(() => clearInterval(intId), 1000);

它打印出这样的东西:

T: 1164.656 P.now:1176.300000000083

我想知道12ms的差异是什么原因?执行一些用requestAnimationFrame注册的其他回调需要一些时间?这只是与解释 js 相关的一些开销?或者是什么?在这种情况下,我不会放弃 12 毫秒。

最佳答案

参数是一个 DOMHighResTimeStamp ,就像什么Performance.now应该返回,即使它不是此方法返回的那个。


所以首先让我们解释一下您所看到的精度差异:最近在大多数 CPU 中发现了一个重大安全问题,已知问题为 Meltdown and Spectre。 .
这些攻击可以从 Web 浏览器进行,但需要 Performance.now 返回的 DOMHighResTimeStamp。 Firefox 发现,快速修复/“缓解措施”是降低此 DOMHighResTimeStamp 的分辨率。 (see more).

由于 requestAnimationFrame 回调计划触发下一帧(即上次调用后约 16 毫秒),从此方法传递的 DOMHighResTimeStamp 不需要此缓解措施,因此您在 this DOMHighResTimeStamp 中仍然具有完整的精度。


现在回答题主的问题,在requestAnimationFrame的回调中传入的DOMHighResTimeStamp应该代表这一帧所有回调栈的调用时间。
事实上,requestAnimationFrame 仅将回调参数存储在一个堆栈中,然后在帧出现时调用此堆栈中的所有回调(就在下一个绘画操作之前)。< br/>这意味着同一帧的所有回调将共享完全相同的 DOMHighResTimeStamp,而不管前一个回调花费了多长时间。

但是需要注意的是,在 Chrome 和 Firefox 中,时间戳实际上是在浏览器接收到显示器的 V-Sync 信号时设置的,而不是在它们调用回调时设置的。 这解释了在使用 performance.now() 测量 rAF() 与回调中传递的时间戳之间的时间时可能会出现负面结果的罕见情况。

function long(time){
var now = performance.now();
console.log('long');
console.log({
'rAF time': time,
'Performance time': now,
'diff': (now - time) + 'ms'
});
console.log('________________________');
// wait 50ms
while(performance.now() - time < 50) {
}
}
function short(time) {
var now = performance.now();
console.log('short');
console.log({
'rAF time': time,
'Performance time': now,
'diff': (now - time) + 'ms'
});
}
// our two functions will be stacked together to fire in the same frame
requestAnimationFrame(long);
requestAnimationFrame(short);

关于javascript - requestAnimationFrame 回调中的参数到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50311887/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com