typescript
★ Featured
Debounce Function
A simple debounce utility to limit function execution rate
#utility
#performance
#events
function debounce<T extends (...args: unknown[]) => unknown>(
fn: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}
Debounce Function
A debounce function limits how often a function can be called. Useful for search inputs, window resize handlers, and scroll events.
Usage
const debouncedSearch = debounce((query: string) => { console.log('Searching for:', query);}, 300);
// Only executes 300ms after the last callinput.addEventListener('input', (e) => { debouncedSearch(e.target.value);});When to Use
- Search input autocomplete
- Window resize handlers
- Scroll event listeners
- Form validation on input