0Pricing
JavaScript Academy · Lesson

Debounce vs Throttle — hand-rolled

Build tiny debounce and throttle utilities. Practice trailing and leading variants and know when to pick each.

Overview

Goal: Control noisy events.

  • Debounce: wait for quiet, then run once
  • Throttle: run at most once per interval
  • Leading vs trailing calls
  • Tiny, readable helpers
Debounce vs Throttle — hand-rolled — illustration 1

Debounce (trailing)

Trailing debounce resets a timer on each event and runs once when things calm down.

// Debounce (trailing): run once after events stop
function debounce(fn, wait) {
  let t = null;
  return function (...args) {
    clearTimeout(t);
    t = setTimeout(function () {
      fn.apply(null, args);
    }, wait);
  };
}

// Simulate rapid events: only the last triggers the call
const debouncedLog = debounce(function (msg) {
  console.log("debounced:", msg);
}, 10);

for (let i = 0; i < 5; i++) {
  setTimeout(function () {
    debouncedLog("final after bursts");
  }, i * 3);
}
Debounce vs Throttle — hand-rolled — illustration 2

All lessons in this course

  1. setTimeout, setInterval, and timer drift
  2. Debounce vs Throttle — hand-rolled
  3. Animation Timing — intro with time-based loops
← Back to JavaScript Academy