/** * 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 any>( fn: T, wait: number, ): (...args: Parameters) => void { let timeoutId: ReturnType | null = null; return (...args: Parameters) => { if (timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(() => { fn(...args); timeoutId = null; }, wait); }; }