I\'m trying to implement debouncing in React on the resize
event, using requestAnimationFrame
and wrote the following simple CodePen:
https://c
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.