-
-
Save johnloy/c0c5c31a70ba1ba19b98e7d6d95928f3 to your computer and use it in GitHub Desktop.
Debounce with requestAnimationFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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