Debounce Function
This snippet implements a debounce function to optimize event handling.
This snippet demonstrates how to create a debounce function, which delays the execution of a function until after a specified delay has passed since the last time it was invoked. This is useful for optimizing event handlers like key presses or window resizing.
How It Works
A debounce function ensures that a function is only executed after a specified delay has elapsed since the last invocation. If the function is called again before the delay expires, the timer resets. This helps in situations where frequent event triggers can cause performance issues, such as:
- Handling user input in a search bar
- Optimizing window resize events
- Preventing excessive API calls on rapid user actions
main.ts
function debounce<T extends (...args: any[]) => void>(func: T, delay: number): T {
let timer: ReturnType<typeof setTimeout>;
return function (...args: Parameters<T>) {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
} as T;
}
const logMessage = debounce((msg: string) => console.log(msg), 500);
logMessage("Hello");
logMessage("World");
When to Use Debounce
- Search fields: Avoids making too many API requests as the user types.
- Window resizing: Prevents excessive recalculations.
- Button clicks: Prevents multiple form submissions.