Skip to content

JS: A Simple Debounce Function

Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often that they cripple the performance of the web page. A debounce function waits until a certain amount of time has passed without the event being triggered before executing the callback. It’s perfect for search input, window resizing, or scroll events.

function debounce(func, delay) {
    let timeoutId;

    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}

Leave a Comment

Your email address will not be published.