Skip to content

Instantly share code, notes, and snippets.

@johnloy
Forked from rpemberton/debounce.js
Created June 6, 2022 14:11
Show Gist options
  • Save johnloy/c0c5c31a70ba1ba19b98e7d6d95928f3 to your computer and use it in GitHub Desktop.
Save johnloy/c0c5c31a70ba1ba19b98e7d6d95928f3 to your computer and use it in GitHub Desktop.
Debounce with requestAnimationFrame
// Useful for debouncing callbacks to mousemove, resize, scroll event listeners
function debounce(fn) {
let raf;
return (...args) => {
if (raf) {
console.log('debounced');
return;
}
raf = window.requestAnimationFrame(() => {
fn(...args); // run useful code
raf = undefined;
});
};
}
function handleMouseMove(e) {
console.log('handleMouseMove', e);
}
const debouncedHandleMouseMove = debounce(handleMouseMove);
document.addEventListener('mousemove', debouncedHandleMouseMove);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment