performance.now 和 document.timeline.currentTime

问题描述 投票:0回答:1

MDN performance.now():

performance.now() 方法返回高分辨率时间戳(以毫秒为单位)。它表示自 Performance.timeOrigin

以来经过的时间

MDN 文档.时间线.当前时间

此时间线表示自 Performance.timeOrigin 以来的时间(以毫秒为单位)。

网页动画:

此外,由于默认文档时间线的时间值与时间原点的偏移量为零,因此 document.timeline.currentTime 将大致对应于 Performance.now()

console.log(performance.now(), document.timeline.currentTime)

具有不同的值。为什么?

javascript dom performance.now
1个回答
0
投票

因为时间线的 currentTime 仅在 Web 动画时更新,即在事件循环的 更新渲染步骤中。

因此,如果您在循环期间不断请求

currentTime
,您将只能得到一个值:

const timestamps = new Set();
const t1 = performance.now();
while (performance.now() - t1 < 3000) { // perform below code for 3s
  timestamps.add(document.timeline.currentTime);
}
console.log([...timestamps]); // a single value

请注意,此时间戳应该与传递给 Window 上下文中的

requestAnimationFrame
回调的时间戳相同:

let i = 0;
const anim = (timestamp) => {
  console.log('same timestamps', timestamp === document.timeline.currentTime);
  if (i++ < 10)
    requestAnimationFrame(anim);
}
requestAnimationFrame(anim);

© www.soinside.com 2019 - 2024. All rights reserved.