Skip to content
  • Debounce & Throttle · JavaScript

Debounce & Throttle

LearnViaNotes @learnvianotes· 2 min read

Two ways to rate-limit a function that fires too often (typing, scrolling, resizing): debounce waits for quiet, throttle runs at most once per interval.

Debounce

JavaScript
function debounce(fn, wait) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), wait);
  };
}

const search = debounce((q) => console.log("searching for:", q), 30);
search("j");
search("ja");
search("jav");                          // only this one survives the burst
setTimeout(() => search("javascript"), 60);
Output
searching for: jav
searching for: javascript

Throttle

JavaScript
function throttle(fn, wait) {
  let last = 0, timer = null, pendingArgs = null;
  return function (...args) {
    const now = Date.now();
    const remaining = wait - (now - last);
    if (remaining <= 0) {               // leading call
      last = now;
      fn.apply(this, args);
    } else {                            // remember the latest call for the trailing edge
      pendingArgs = args;
      timer ??= setTimeout(() => {
        last = Date.now();
        timer = null;
        fn.apply(this, pendingArgs);
      }, remaining);
    }
  };
}

const onScroll = throttle((y) => console.log("handle scroll at", y), 50);
onScroll(0);                  // runs immediately (leading edge)
onScroll(10);                 // ignored…
onScroll(20);                 // …but the latest is kept for the trailing edge
Output
handle scroll at 0
handle scroll at 20
DebounceThrottle
RunsOnce, after the burst endsRegularly during the burst
GuaranteeLatest value, eventuallyAt most one call per wait
Typical useSearch box, validation, auto-saveScroll, resize, drag, analytics

Debounce vs throttle?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report