|
| 1 | +type DebouncedFunction<T extends (...args: any[]) => void> = T & { |
| 2 | + cancel: () => void; |
| 3 | +}; |
| 4 | + |
| 5 | +export default function debounce<T extends (...args: any[]) => void>( |
| 6 | + fn: T, |
| 7 | + delay: number, |
| 8 | + { leading = false }: { leading?: boolean } = {} |
| 9 | +): DebouncedFunction<T> { |
| 10 | + let timeoutId: ReturnType<typeof setTimeout> | undefined; |
| 11 | + let isLeadingInvoked = false; |
| 12 | + let lastThis: unknown; |
| 13 | + let lastArgs: Parameters<T> | undefined; |
| 14 | + |
| 15 | + const debounced = function (this: unknown, ...args: Parameters<T>) { |
| 16 | + lastThis = this; |
| 17 | + lastArgs = args; |
| 18 | + |
| 19 | + if (leading && !isLeadingInvoked) { |
| 20 | + isLeadingInvoked = true; |
| 21 | + fn.apply(this, args); |
| 22 | + lastArgs = undefined; // Clear so we can detect subsequent calls |
| 23 | + } |
| 24 | + |
| 25 | + if (timeoutId !== undefined) { |
| 26 | + clearTimeout(timeoutId); |
| 27 | + } |
| 28 | + |
| 29 | + timeoutId = setTimeout(() => { |
| 30 | + const thisCtx = lastThis; |
| 31 | + const thisArgs = lastArgs; |
| 32 | + // Reset state BEFORE calling fn so re-entrant calls work correctly |
| 33 | + isLeadingInvoked = false; |
| 34 | + timeoutId = undefined; |
| 35 | + lastArgs = undefined; |
| 36 | + |
| 37 | + if (!leading) { |
| 38 | + fn.apply(thisCtx, thisArgs!); |
| 39 | + } else if (thisArgs !== undefined) { |
| 40 | + // Leading+trailing: only fire trailing if there were calls after the leading |
| 41 | + fn.apply(thisCtx, thisArgs); |
| 42 | + } |
| 43 | + }, delay); |
| 44 | + } as DebouncedFunction<T>; |
| 45 | + |
| 46 | + debounced.cancel = () => { |
| 47 | + if (timeoutId !== undefined) { |
| 48 | + clearTimeout(timeoutId); |
| 49 | + } |
| 50 | + timeoutId = undefined; |
| 51 | + isLeadingInvoked = false; |
| 52 | + lastArgs = undefined; |
| 53 | + }; |
| 54 | + |
| 55 | + return debounced; |
| 56 | +} |
0 commit comments