debounce
Creates a debounced function that delays invoking the provided function until after wait milliseconds have elapsed. Prevents rapid successive calls by canceling previous timeouts. Useful for handling events like search input, button clicks, or window resize where you want to limit the frequency of function execution.
Installation
npx fragmen add function/debounceSource Code
/**
* Creates a debounced function that delays invoking the provided function until after wait milliseconds have elapsed.
*
* Prevents rapid successive calls by canceling previous timeouts. Useful for handling
* events like search input, button clicks, or window resize where you want to limit
* the frequency of function execution.
*
* @tags performance, event-handling
* @param {(...args: Args) => void} fn The function to debounce.
* @param {number} wait The number of milliseconds to delay execution.
* @returns {(...args: Args) => void} A debounced version of the function that accepts the same parameters.
*
* @example
* ```typescript
* const handleSearch = (query: string) => console.log('Searching:', query);
* const debouncedSearch = debounce(handleSearch, 300);
*
* // Multiple rapid calls
* debouncedSearch('a');
* debouncedSearch('ap');
* debouncedSearch('app');
* // Only the last call ('app') will execute after 300ms
*
* const saveData = () => console.log('Saving...');
* const debouncedSave = debounce(saveData, 1000);
* ```
*/
export function debounce<T extends (...args: unknown[]) => void>(
fn: T,
wait: number
): (...args: Parameters<T>) => void {
let timeout: ReturnType<typeof setTimeout> | null = null;
return (...args: Parameters<T>) => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => fn(...args), wait);
};
}
Examples
const handleSearch = (query: string) => console.log('Searching:', query);
const debouncedSearch = debounce(handleSearch, 300);
// Multiple rapid calls
debouncedSearch('a');
debouncedSearch('ap');
debouncedSearch('app');
// Only the last call ('app') will execute after 300ms
const saveData = () => console.log('Saving...');
const debouncedSave = debounce(saveData, 1000);
Related Utilities
memoize
functionCreates a memoized version of a function that caches results. Caches function results based on arguments using a simple key-based cache. Improves performance for expensive pure functions by avoiding redundant calculations. Uses JSON.stringify for key generation.
once
functionCreates a function that can only be invoked once. Subsequent calls return the result of the first invocation. Ensures a function is executed exactly one time, regardless of how many times it's called. Useful for initialization functions, event handlers that should only fire once, or expensive operations that should only run once.
throttle
functionCreates a throttled function that only invokes the provided function at most once per specified time period. Unlike debounce which delays execution, throttle ensures the function is called at regular intervals. The first call is executed immediately, and subsequent calls within the wait period are ignored. Useful for rate-limiting events like scroll, mousemove, or API requests.
Quick Actions
Tags
Parameters
fn(...args: Args) => voidThe function to debounce.
waitnumberThe number of milliseconds to delay execution.
Returns
(...args: Args) => voidA debounced version of the function that accepts the same parameters.