diff options
Diffstat (limited to 'src/lib/search/debounce.ts')
| -rw-r--r-- | src/lib/search/debounce.ts | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/src/lib/search/debounce.ts b/src/lib/search/debounce.ts new file mode 100644 index 0000000..4b685e7 --- /dev/null +++ b/src/lib/search/debounce.ts @@ -0,0 +1,30 @@ +/** + * Creates a debounced version of a function that delays execution until after + * the specified wait time has elapsed since the last invocation. + */ +export function debounce<T extends (...args: any[]) => any>( + func: T, + wait: number +): (...args: Parameters<T>) => void { + let timeoutId: ReturnType<typeof setTimeout> | null = null; + + return function (...args: Parameters<T>) { + if (timeoutId !== null) { + clearTimeout(timeoutId); + } + + timeoutId = setTimeout(() => { + func(...args); + timeoutId = null; + }, wait); + }; +} + +/** + * Clears a timeout if it exists + */ +export function clearDebounce(timeoutId: ReturnType<typeof setTimeout> | null) { + if (timeoutId !== null) { + clearTimeout(timeoutId); + } +} |
