requestAnimationFrame not working as expected

安稳与你 提交于 2019-12-20 03:35:09

问题


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...


回答1:


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.

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.



来源:https://stackoverflow.com/questions/56514486/requestanimationframe-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!