Skip to content

Instantly share code, notes, and snippets.

@kiuKisas
Last active September 13, 2024 15:34
Show Gist options
  • Save kiuKisas/4e3189090691899934ec62c17214272a to your computer and use it in GitHub Desktop.
Save kiuKisas/4e3189090691899934ec62c17214272a to your computer and use it in GitHub Desktop.
An identity function that debounce an event listener based on FPS
// 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