File size: 1,636 Bytes
4e1096a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | interface DebounceOptions {
emitLast?: boolean;
}
/**
* Debounces a function by waiting `delay` ms after the last call before executing it.
* If `emitLast` is false, it cancels the call instead of delaying it.
*
* @returns A debounced function with additional `flush` and `cancel` methods.
*/
export const debounce = <T extends (...args: Parameters<T>) => void | Promise<void>>(
func: T,
delay: number,
options: DebounceOptions = { emitLast: true },
): ((...args: Parameters<T>) => void) & { flush: () => void; cancel: () => void } => {
let timeout: ReturnType<typeof setTimeout> | null = null;
let lastArgs: Parameters<T> | null = null;
const debounced = (...args: Parameters<T>): void => {
lastArgs = args;
if (timeout) {
clearTimeout(timeout);
}
if (options.emitLast) {
timeout = setTimeout(() => {
if (lastArgs) {
func(...(lastArgs as Parameters<T>));
lastArgs = null;
}
timeout = null;
}, delay);
} else {
timeout = setTimeout(() => {
func(...args);
timeout = null;
}, delay);
}
};
/**
* Immediately executes the last pending debounced function call.
*/
debounced.flush = () => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
if (lastArgs) {
func(...(lastArgs as Parameters<T>));
lastArgs = null;
}
}
};
/**
* Cancels the pending debounced function call.
*/
debounced.cancel = () => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
lastArgs = null;
}
};
return debounced;
};
|