shaky.sh

Throttle vs. Debounce

This might just be me, but I confuse debounce and throttle. I can never remember the difference. This post should help me remember the difference.

Neither

Every mousemove event on the div below increments the counter:

Neither: triggered 0 times

Throttle

function throttle(fn, ms) {
    let id;
    return () => {
        if (id) return;
        id = setTimeout(() => {
            fn();
            id = undefined;
        }, ms);
    };
}

When using throttle, your function will run at most once per interval, no matter how many times it is triggered in that interval.

Throttle 200ms: triggered 0 times

Debounce

function debounce(fn, ms) {
    let id;
    return () => {
        if (id) clearTimeout(id);
        id = setTimeout(fn, ms);
    };
}

When using debounce, your function will run after it has not been triggered for a full interval.

Debounce 200ms: triggered 0 times