Skip to content

Instantly share code, notes, and snippets.

@rpemberton
Last active March 3, 2024 03:20
Show Gist options
  • Save rpemberton/b15a206f453ff233830f3183e4ac371a to your computer and use it in GitHub Desktop.
Save rpemberton/b15a206f453ff233830f3183e4ac371a 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