← Back to Node.js, page 10

nodejs-0192 · Easy fresher

Implement debounce and throttle. What is the difference, and when do you use each?

Debounce waits until calls stop for a given time, then runs once with the last arguments (search box typing, resize end). Throttle runs at most once per interval while calls keep coming (scroll handlers, progress updates, rate-limited work). Both are closures around a timer. Add cancel (and flush for debounce) so the timers can be cleaned up.

Full answer

Debounce

  • Keep a timer id in a closure. On every call, clear the old timer and start a new one. Only when the quiet period passes does the function run, with the arguments of the last call.
  • Option leading: run on the first call and ignore the rest until the quiet period ends.
  • Add cancel() to clear the timer, so a pending call does not run after shutdown or unmount.

Throttle

  • Allow a call, then ignore calls until the interval has passed. A common version runs the first call at once (leading) and, if calls came in during the wait, runs the last one at the end of the interval (trailing), so the final state is not lost.
  • It limits the rate of calls, but does not delay a single call.

Choosing

  • Debounce: you care about the final value after a burst (autosave after typing, search suggestions).
  • Throttle: you care about regular updates during a burst (logging progress, scroll or mouse move).

Testing: inject a clock (setTimeout, clearTimeout and now) so tests do not sleep. Real code in Node can use timers with unref() so a pending timer does not keep the process alive.

javascript
// A small fake clock, so the example does not need to wait.
function createClock() {
  let now = 0, nextId = 1; const timers = new Map();
  return {
    now: () => now,
    setTimeout(fn, ms) { const id = nextId++; timers.set(id, { at: now + ms, fn }); return id; },
    clearTimeout(id) { timers.delete(id); },
    advance(ms) {
      const target = now + ms;
      for (;;) {
        const due = [...timers].filter(([, t]) => t.at <= target).sort((a, b) => a[1].at - b[1].at)[0];
        if (!due) break;
        now = due[1].at; timers.delete(due[0]); due[1].fn();
      }
      now = target;
    },
  };
}

function debounce(fn, wait, { leading = false, clock = globalThis } = {}) {
  let timer, lastArgs;
  function debounced(...args) {
    lastArgs = args;
    const callNow = leading && timer === undefined;
    clock.clearTimeout(timer);
    timer = clock.setTimeout(() => { timer = undefined; if (!leading) fn.apply(this, lastArgs); }, wait);
    if (callNow) fn.apply(this, args);
  }
  debounced.cancel = () => { clock.clearTimeout(timer); timer = undefined; };
  return debounced;
}

function throttle(fn, interval, { clock = globalThis } = {}) {
  let last = -Infinity, timer, pendingArgs;
  function throttled(...args) {
    const wait = interval - (clock.now() - last);
    if (wait <= 0) { last = clock.now(); fn.apply(this, args); return; }
    pendingArgs = args;                                          // keep the latest call for the trailing run
    timer ??= clock.setTimeout(() => { timer = undefined; last = clock.now(); fn.apply(this, pendingArgs); }, wait);
  }
  throttled.cancel = () => { clock.clearTimeout(timer); timer = undefined; };
  return throttled;
}

const clock = createClock();

const saved = [];
const save = debounce((text) => saved.push(text), 100, { clock });
save('h'); clock.advance(30); save('he'); clock.advance(30); save('hel');
console.log('debounce: before the quiet period:', JSON.stringify(saved));
clock.advance(100);
console.log('debounce: after the quiet period :', JSON.stringify(saved));

const leadingCalls = [];
const leading = debounce((x) => leadingCalls.push(x), 100, { leading: true, clock });
leading('a'); leading('b'); leading('c');
console.log('debounce leading                 :', JSON.stringify(leadingCalls));

const ticks = [];
const log = throttle((x) => ticks.push(`${x}@${clock.now()}`), 100, { clock });
const start = clock.now();
for (let i = 0; i < 10; i++) { log(i); clock.advance(30); }
clock.advance(100);
console.log('throttle over 300 ms (10 calls)  :', ticks.map((t) => t.replace(/@(\d+)/, (m, n) => '@+' + (n - start))).join(', '));

A fake clock makes the timing exact, so every run prints the same result. The real setTimeout would give the same logic with small timing variations. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): debounce: before the quiet period: [] debounce: after the quiet period : ["hel"] debounce leading : ["a"] throttle over 300 ms (10 calls) : 0@+0, 3@+100, 6@+200, 9@+300

Key points

  • Debounce runs after calls stop; throttle runs at most once per interval.
  • Both use a closure with timer state.
  • Debounce uses the last arguments.
  • Throttle often has leading and trailing calls.
  • Provide cancel and test with a fake clock.

Common mistakes

  • Creating the debounced function inside a render or request handler, so state is never shared.
  • Losing this or the arguments.
  • Using throttle when only the final value matters.
  • Leaving timers pending after shutdown.
  • Mixing up the two names in an explanation.

Follow-ups

  • How would you add a maxWait option to debounce?
  • How does lodash implement leading and trailing?
  • How do you test timer code without waiting?

Tips

  • Use a one-line definition for each.
  • Give one use case each.
  • Mention cancel and a fake clock.