requestAnimationFrame not working as expected

后端 未结 1 498
小蘑菇
小蘑菇 2021-01-21 23:46

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

https://c

相关标签:
1条回答
  • 2021-01-21 23:57

    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.

    0 讨论(0)
提交回复
热议问题