debounce
Description
The debounce utility function limits the rate at which a function can be executed. It delays the
execution of a function until after a specified timeout has passed since the last time it was invoked.
Basic Usage
Import and use the debounce function to limit function execution frequency:
import debounce from './utils/debounce.js';
const handleSearch = debounce((query) => {
console.log('Searching for:', query);
}, 300);
// Will only execute after 300ms of no calls
handleSearch('test');
Parameters
func: Function
The function to debounce.
timeout: number (optional)
The number of milliseconds to delay execution. Defaults to 300ms.
Examples
Search Input Debouncing
const debouncedSearch = debounce((searchTerm) => {
// API call or expensive search operation
performSearch(searchTerm);
}, 500);
searchInput.addEventListener('input', (e) => {
debouncedSearch(e.target.value);
});
Window Resize Handler
const debouncedResize = debounce(() => {
// Expensive layout calculations
recalculateLayout();
}, 250);
window.addEventListener('resize', debouncedResize);