gpt4 book ai didi

javascript - 为什么 requestAnimationframe 为某些帧多次调用,而对于其他帧则根本不调用?

转载 作者:行者123 更新时间:2023-12-04 14:00:59 25 4
gpt4 key购买 nike

我有一个使用 requestAnimationFrame 的 redux 应用程序在每个 TICK 上呈现一个新状态,但是 Google Chrome 似乎正在调用 requestAnimationFrame对于某些滴答声最多 3 次(!!),而对于其他滴答声则完全没有,导致动画卡顿。

在 React 开发模式下:
Chrome performance timeline screenshot 1
在 react 中 NODE_ENV=production模式:
Chrome performance timeline screenshot 2

它已经以 60fps 渲染,所以多个不必要的 requestAnimationFrame每 16ms 帧的回调非常浪费 CPU 资源。没有刻度的帧也会导致动画滞后。我的滴答函数只需要 4 毫秒来计算(远低于 16 毫秒的预算),而且我只有一个回调在页面上运行。

这是处理在每个刻度上调度我的 redux 调用的动画代码。

class AnimationHandler {
constructor(store) {
this.store = store
this.animating = false
store.subscribe(::this.handleStateChange)
}
handleStateChange() {
if (!this.animating) {
this.tick()
}
}
tick(timestamp) {
this.animating = true
this.store.dispatch({
type: 'TICK',
current_timestamp: (new Date).getTime(),
// reducer handles updating rendered state to this point in time
})
window.requestAnimationFrame(::this.tick)
}
}

window.animations = new AnimationHandler(window.store) // redux store

什么可能导致 Chrome 这样做,我该如何做到这一点,以便有一个一致的 tick()每帧渲染调用,不多不少?

最佳答案

我有同样的问题。这是我这边的一个错误,我怀疑它总是如此。
在您的代码中,调用 tick()调度 requestAnimationFrame 的无限循环,因为 requestAnimationFrame() 总是作为 tick() 的一部分被调用。这是正常的。
如果 tick() 没有问题仅在循环外调用一次。这在您的示例中没有发生,但您可能在实际应用程序中启动了多个循环。
以防万一,我会将您的代码更改为:

handleStateChange() {
if (!this.animating) {
this.animating = true // immediate
this.tick()
}
}
就我而言,我正在重用 tick()方法,添加层层的 requestAnimationFrame()。
示例:(错误!)
// init
window.requestAnimationFrame(tick)

// on some other events
tick() // WRONG! will create a new layer of requestAnimationFrame loop!

关于javascript - 为什么 requestAnimationframe 为某些帧多次调用,而对于其他帧则根本不调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44793149/

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