mirror of
https://github.com/zoriya/v10.git
synced 2026-08-16 02:45:09 +00:00
31 lines
783 B
TypeScript
31 lines
783 B
TypeScript
/** A throttled function that can be cancelled. */
|
|
export interface RafThrottled<Args extends unknown[]> {
|
|
(...args: Args): void;
|
|
/** Cancel any pending animation frame. */
|
|
cancel(): void;
|
|
}
|
|
|
|
/** Throttle a function to fire at most once per animation frame. */
|
|
export function rafThrottle<Args extends unknown[]>(fn: (...args: Args) => void): RafThrottled<Args> {
|
|
let rafId: number | null = null;
|
|
let latestArgs: Args;
|
|
|
|
const throttled = (...args: Args): void => {
|
|
latestArgs = args;
|
|
if (rafId !== null) return;
|
|
rafId = requestAnimationFrame(() => {
|
|
rafId = null;
|
|
fn(...latestArgs);
|
|
});
|
|
};
|
|
|
|
throttled.cancel = (): void => {
|
|
if (rafId !== null) {
|
|
cancelAnimationFrame(rafId);
|
|
rafId = null;
|
|
}
|
|
};
|
|
|
|
return throttled;
|
|
}
|