Last active
September 13, 2024 15:34
-
-
Save kiuKisas/4e3189090691899934ec62c17214272a to your computer and use it in GitHub Desktop.
An identity function that debounce an event listener based on FPS
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
// identity function that debounce an event listener based on FPS | |
function fpsDebounceEventListener(listener: EventListener): EventListener { | |
let rafId: number; | |
// raf wrapper | |
const rafListener = (e: Event) => { | |
if (rafId) cancelAnimationFrame(rafId); | |
rafId = requestAnimationFrame(() => listener(e)); | |
}; | |
return rafListener; | |
} | |
// Example | |
function myEventHandler() { | |
// Do whatever you have to | |
} | |
const myDebouncedEventHandler = fpsDebounceEventListener(myEventHandler); | |
// can be shared across events | |
window.addEventListener("resize", myDebouncedEventHandler); | |
window.addEventListener("mousemove", myDebouncedEventHandler); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment