requestAnimationFrame无法正常工作 [英] requestAnimationFrame not working as expected

查看:110
本文介绍了requestAnimationFrame无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 requestAnimationFrame resize 事件上实现React的反跳操作,并编写了以下简单内容CodePen:



  Chrome Firefox边缘

只有边缘的行为符合我的预期。



我是误解了什么还是打算?



尽管Edge和另外两个之间还有另一个不一致之处:最大化窗口时,一次触发resize事件Edge,并在Chrome和Firefox上两次。
应该没什么大问题,但是我很好奇背后的原因...

解决方案

您对requestAnimationFrame的理解可能是正确的。这里发生的是,当今的浏览器确实已经将 resize 事件反跳到屏幕刷新率根据规范



这可以通过添加两个事件侦听器来演示,一个侦听器和一个 nude



  addEventListener('resize',e => console.log('non-debounced')); let active = null; addEventListener('resize',e => { (活动){console.log( cancelling); cancelAnimationFrame(活动);} active = requestAnimationFrame(()=> {console.log('debounced'); active = null;});});  



在上述两种浏览器中,日志均为


未反跳

已反跳

未反跳

已反跳

...


事实证明,只有两个去抖事件处理程序在两个去抖的事件之间触发



因此,由于这些事件已被消除,因此您的消除反弹器代码将永远无法到达。


I'm trying to implement debouncing in React on the resize event, using requestAnimationFrame and wrote the following simple CodePen:

https://codepen.io/robloche/pen/RmLjZV

But the behaviour is not consistent across Chrome (v75), Firefox (v67) and Edge (v42), although the MDN states that it should be.

When I resize the window, quickly dragging the edge back and forth, here's what's displayed in the console:

Chrome                      Firefox                    Edge

Only edge behaves as I expected.

Am I misunderstanding something or is this intended?

Although, there's another inconsistency between Edge and the other two: when maximizing the window, the resize event is triggered once on Edge and twice on Chrome and Firefox. That shouldn't be much of a problem, but I'm curious about the reason behind...

解决方案

Your understanding of requestAnimationFrame might be correct. What happens here is that browsers nowadays do already debounce the resize event to the screen refresh rate, in accordance to the specs.

This can be demonstrated by adding two event listeners, one debounced and one nude:

addEventListener('resize', e => console.log('non-debounced'));
let active = null;
addEventListener('resize', e => {
  if(active) {
    console.log("cancelling");
    cancelAnimationFrame(active);
  }
  active = requestAnimationFrame(() => {
    console.log('debounced');
    active = null;
  });
});

In both aforementioned browsers, the log will be

non-debounced
debounced
non-debounced
debounced
...

The fact that only a single "non-debounced" event handler fired in between two debunced ones proves that even the non-debounced version is actually debounced, by the browser.

So since these event are already debounced, your debouncer code is never reached.

这篇关于requestAnimationFrame无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆