只需运行以下命令:
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的一些开销?要不然是啥?在这种情况下,我不会扔掉12ms的东西。
该参数是一个DOMHighResTimeStamp,就像Performance.now应该返回的一样,即使它不是此方法返回的那个也是如此。
因此,首先让我们解释一下您所看到的精度差异:最近,在大多数CPU中发现了一个主要的安全问题,该问题被称为Meltdown和Spectre。
这些攻击可以从Web浏览器来犯,但需要DOMHighResTimeStamp返回由Performance.now。Firefox发现,一种快速修复/“缓解”措施是降低此DOMHighResTimeStamp的分辨率。(查看更多)。
由于requestAnimationFrame回调预计火下一帧(即以前的〜电话后16毫秒)的DOMHighResTimeStamp从这个方法传递不需要这种缓解,因此,你仍然有在全精度此 DOMHighResTimeStamp。
现在要回答标题的问题,传入requestAnimationFrame
的回调中的DOMHighResTimeStamp表示此帧的所有回调堆栈的调用时间。
实际上,requestAnimationFrame仅将回调参数存储在堆栈中,然后在发生帧时(恰好在下一个绘画操作之前)调用此堆栈。
这意味着同一帧的所有回调将共享完全相同的DOMHighResTimeStamp,而无需考虑前一个回调花费了多长时间。
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句