Created
May 24, 2022 09:57
-
-
Save jeongtae/19bdc29c4b3bb58d3d049d491785b35d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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