JAVASCRIPT
Debounce a JavaScript DOM Event Handler
Implement a reusable debounce function in plain JavaScript to limit how often a DOM event handler fires, improving performance for search inputs, window resizing, or scroll events.
/**
* Debounce a function to limit how often it's called.
* @param {Function} func The function to debounce.
* @param {number} delay The delay in milliseconds.
* @returns {Function} The debounced function.
*/
const debounce = (func, delay) => {
let timeoutId;
return function(...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(context, args), delay);
};
};
// Example usage with a search input
document.addEventListener('DOMContentLoaded', () => {
const searchInput = document.getElementById('searchInput');
if (searchInput) {
const handleSearchInput = (event) => {
console.log('Searching for:', event.target.value);
// Perform search logic here (e.g., fetch data from API)
};
const debouncedSearch = debounce(handleSearchInput, 500); // 500ms delay
searchInput.addEventListener('input', debouncedSearch);
console.log('Debounced search input listener attached.');
}
});
/* Example HTML for context:
<input type="text" id="searchInput" placeholder="Type to search...">
*/
How it works: This snippet provides a general-purpose `debounce` function for plain JavaScript, useful for limiting how frequently a function (typically an event handler) is executed. It's particularly valuable for performance-critical DOM events like `input` (for search fields), `resize` (for window resizing), or `scroll`. The `debounce` function ensures that the wrapped function (`func`) is only called after a specified `delay` has passed without any further invocations. If the event fires again within the delay, the previous timer is cleared, and a new one is set, effectively waiting for a pause in user activity before executing the logic.