Blog>
Snippets

Debounced Input Validation

Introduce debounced validation for a search input or similar, where the form waits for a pause in typing before validating and perhaps sending an API request.
// Function to perform validation or send an API request
function validateInput(value) {
    // Perform input validation logic or send an API request
    console.log('Validating:', value);
    // Placeholder for actual validation or API request logic
}

// Debounce function to limit how often our validate function is called
function debounce(func, delay) {
    let timerId;
    return function(...args) {
        clearTimeout(timerId);
        timerId = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}

// Attach debounced validation to an input element
const searchInput = document.querySelector('#search-input');
const debouncedValidate = debounce(validateInput, 500); // Delay of 500ms

searchInput.addEventListener('input', (event) => {
    debouncedValidate(event.target.value);
});
This code provides a debounced input validation mechanism. First, a `validateInput` function is defined, which should contain the actual validation logic or API request. A `debounce` function is then provided, which takes any function and a delay, returning a new function executing only after a specified quiet period. An event listener is added to the search input field, invoking the debounced `validateInput` function every time the user types, with a 500ms pause in typing required before the function is executed.