Search code examples
javascriptreactjsrequestanimationframedebouncing

requestAnimationFrame not working as expected


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:

Resizing console output on Chrome Resizing console output on Firefox Resizing console output on Edge

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


Solution

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