41 lines
934 B
TypeScript
41 lines
934 B
TypeScript
export type Debounced<Args extends unknown[]> = ((...args: Args) => void) & {
|
|
flush: () => void;
|
|
cancel: () => void;
|
|
};
|
|
|
|
export function debounce<Args extends unknown[]>(
|
|
fn: (...args: Args) => void,
|
|
waitMs: number
|
|
): Debounced<Args> {
|
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
let pendingArgs: Args | null = null;
|
|
|
|
const debounced = (...args: Args): void => {
|
|
pendingArgs = args;
|
|
if (timer !== null) clearTimeout(timer);
|
|
timer = setTimeout(() => {
|
|
timer = null;
|
|
const a = pendingArgs!;
|
|
pendingArgs = null;
|
|
fn(...a);
|
|
}, waitMs);
|
|
};
|
|
|
|
debounced.flush = (): void => {
|
|
if (timer === null) return;
|
|
clearTimeout(timer);
|
|
timer = null;
|
|
const a = pendingArgs!;
|
|
pendingArgs = null;
|
|
fn(...a);
|
|
};
|
|
|
|
debounced.cancel = (): void => {
|
|
if (timer !== null) clearTimeout(timer);
|
|
timer = null;
|
|
pendingArgs = null;
|
|
};
|
|
|
|
return debounced;
|
|
}
|