JAVASCRIPT
Debounce an Input Event Handler
Create a custom debounce function for JavaScript event handlers, perfect for optimizing performance of input fields, search bars, or resize events by delaying execution until a pause in activity.
const debounce = (func, delay) => {
let timeoutId;
return function(...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(context, args), delay);
};
};
// Example Usage:
// HTML: <input type="text" id="searchInput" placeholder="Type to search...">
// const searchInput = document.getElementById('searchInput');
// const handleSearch = (event) => {
// console.log('Searching for:', event.target.value);
// // Perform actual search API call or DOM update here
// };
// const debouncedSearch = debounce(handleSearch, 500);
// searchInput.addEventListener('input', debouncedSearch);
How it works: This snippet provides a generic `debounce` utility function that can be applied to any event handler. Debouncing delays the execution of a function until a specified `delay` has passed without the function being called again. This is extremely valuable for events that fire frequently, such as `input` on a text field (to prevent excessive API calls), `resize`, or `scroll`, preventing performance issues and improving user experience by executing the heavy logic only when the user has paused their interaction.