44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
|
|
/**
|
||
|
|
* ============================================================================
|
||
|
|
* DEBOUNCE UTILITY
|
||
|
|
* ============================================================================
|
||
|
|
*
|
||
|
|
* Creates a debounced function that delays execution until after wait milliseconds
|
||
|
|
* have elapsed since the last time it was invoked.
|
||
|
|
*
|
||
|
|
* @example
|
||
|
|
* ```typescript
|
||
|
|
* const debouncedSearch = debounce((query: string) => {
|
||
|
|
* console.log('Searching for:', query);
|
||
|
|
* }, 300);
|
||
|
|
*
|
||
|
|
* debouncedSearch('hello');
|
||
|
|
* debouncedSearch('hello world'); // Only this will execute after 300ms
|
||
|
|
* ```
|
||
|
|
*/
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Creates a debounced version of a function
|
||
|
|
*
|
||
|
|
* @param fn - The function to debounce
|
||
|
|
* @param wait - The delay in milliseconds
|
||
|
|
* @returns A debounced function that will execute after the specified delay
|
||
|
|
*/
|
||
|
|
export function debounce<T extends (...args: any[]) => any>(
|
||
|
|
fn: T,
|
||
|
|
wait: number,
|
||
|
|
): (...args: Parameters<T>) => void {
|
||
|
|
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||
|
|
|
||
|
|
return (...args: Parameters<T>) => {
|
||
|
|
if (timeoutId) {
|
||
|
|
clearTimeout(timeoutId);
|
||
|
|
}
|
||
|
|
|
||
|
|
timeoutId = setTimeout(() => {
|
||
|
|
fn(...args);
|
||
|
|
timeoutId = null;
|
||
|
|
}, wait);
|
||
|
|
};
|
||
|
|
}
|