Skip to content

Instantly share code, notes, and snippets.

@jeongtae
Created May 24, 2022 09:57
Show Gist options
  • Save jeongtae/19bdc29c4b3bb58d3d049d491785b35d to your computer and use it in GitHub Desktop.
Save jeongtae/19bdc29c4b3bb58d3d049d491785b35d to your computer and use it in GitHub Desktop.
type AnyFunction = (...args: any) => void;
export function rafThrottle<T extends AnyFunction>(func: T) {
let rafHandle: number | null = null;
const throttled: {
(this: ThisType<T> | void, ...args: Parameters<T>): void,
cancel(): void,
} = Object.assign(
function (this: any, ...args: any) {
if (rafHandle) {
return;
}
rafHandle = requestAnimationFrame(() => {
rafHandle = 0;
func.apply(this, args);
});
},
{
cancel() {
if (rafHandle) {
cancelAnimationFrame(rafHandle);
}
},
},
);
return throttled;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment