Files
browserlay/src/lib/debounce.ts
Michael Chihlas 7bfc09207d feat: debounce helper with flush
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 17:47:25 -04:00

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;
}