Logics Guru

Debounce a Function in Vanilla JavaScript

A dependency-free debounce with immediate-mode support.

javascript JavaScript
javascript
export function debounce(fn, wait = 200, immediate = false) {
    let timer = null;

    return function debounced(...args) {
        const callNow = immediate && timer === null;

        clearTimeout(timer);

        timer = setTimeout(() => {
            timer = null;
            if (!immediate) fn.apply(this, args);
        }, wait);

        if (callNow) fn.apply(this, args);
    };
}

// Search-as-you-type: wait until typing pauses before hitting the network.
const search = debounce((term) => {
    fetch(`/search/suggest?q=${encodeURIComponent(term)}`)
        .then((r) => r.json())
        .then(render);
}, 180);

input.addEventListener('input', (e) => search(e.target.value));

Plain text: https://logicsguru.com/snippets/debounce-function-vanilla-javascript/raw