JAVASCRIPT

Implementing a Debounce Function for Input Events

Improve performance for frequently triggered DOM events like typing in a search box or window resizing by creating a debounce function, preventing excessive function calls.

// Assume an input field like:
// <input type="text" id="search-input" placeholder="Type to search...">
// <p>Search term: <span id="display-search-term"></span></p>

function debounce(func, delay) {
    let timeout;
    return function(...args) {
        const context = this;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), delay);
    };
}

// Example Usage with an input field:
const searchInput = document.getElementById('search-input');
const displaySearchTerm = document.getElementById('display-search-term');

if (searchInput && displaySearchTerm) {
    const handleSearch = (event) => {
        const searchTerm = event.target.value;
        console.log('Performing search for:', searchTerm);
        displaySearchTerm.textContent = searchTerm;
        // In a real application, you would make an API call here
        // or filter a list based on searchTerm
    };

    // Create a debounced version of handleSearch that only runs 300ms after the last keypress
    const debouncedSearch = debounce(handleSearch, 300);

    searchInput.addEventListener('input', debouncedSearch);
}
How it works: The `debounce` function is a higher-order function that limits the rate at which a function can fire. When an event (like `input` on a search field) is triggered rapidly, the debounced function waits for a specified `delay` after the *last* invocation before executing the original function. This prevents the associated heavy operation (e.g., an API call or complex DOM update) from running too frequently, significantly improving performance and responsiveness, especially in user interfaces with interactive elements.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs