Files
frontend-svelte/src/shared/lib/utils/debounce/debounce.ts

40 lines
1.0 KiB
TypeScript

/**
* Creates a debounced version of a function
*
* Delays function execution until after `wait` milliseconds have elapsed
* since the last invocation. Useful for rate-limiting expensive operations
* like API calls or expensive DOM updates.
*
* @example
* ```ts
* const search = debounce((query: string) => {
* console.log('Searching for:', query);
* }, 300);
*
* search('a');
* search('ab');
* search('abc'); // Only this triggers the function after 300ms
* ```
*
* @param fn - The function to debounce
* @param wait - The delay in milliseconds
* @returns A debounced function that executes after the 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);
};
}