Skip to article content
FrontendXLesson 22 / 30

Debounce and Throttle

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

intermediate · about 40 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Explain the difference between debounce and throttle.
  • Implement debounce that preserves this and arguments.
  • Choose the right rate-limiting pattern for an event.

Overview

#

Two ways to limit calls

Debounce delays a call until the events stop for a quiet period, so only the last call in a burst runs. Throttle allows at most one call per interval, so a steady stream produces regular updates. Debounce fits search-as-you-type and validation; throttle fits scroll, resize and drag.

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

Preserving context

The wrapper must forward this and the arguments to the original function, otherwise a method loses its receiver and its parameters. Using a regular function and apply keeps both. Arrow functions capture the enclosing this, which is wrong when the wrapper is attached as a method.

Leading, trailing and cancellation

A debounce can fire on the leading edge, the trailing edge, or both. A cancel method clears the pending timer, and a flush method runs it immediately. Without cancellation, a component that unmounts can still run a stale callback, which is a common source of memory leaks and errors.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    If a debounced function is called five times within its wait window, how many times does the underlying function run?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    const run = debounce(() => count++, 100);
    run(); run(); run(); run(); run();
    Choose the best answer
  2. Exercise 2Explain

    Explain when you would choose throttle over debounce.

    starter.text
    const onScroll = throttle(update, 100);

    Reveal the reference answer
    reference.text
    Throttle guarantees a call at most once per interval, so it keeps a steady stream of updates while the event is ongoing. That fits scroll, resize and pointer movement, where the user needs continuous feedback. Debounce waits for the events to stop, so it fits search input and save-on-type, where only the final state matters. Choosing the wrong one either floods the work or delays feedback.

    Authored expected output: updates at a fixed rate

    The answer should connect continuous feedback to throttle and settle-then-act to debounce.

  3. Exercise 3Implement

    Implement `throttle(fn, wait)` so fn runs at most once per wait window and the first call runs immediately.

    starter.javascript
    function throttle(fn, wait) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function throttle(fn, wait) {
      let last = 0;
      return function (...args) {
        const now = Date.now();
        if (now - last >= wait) {
          last = now;
          return fn.apply(this, args);
        }
      };
    }

    Authored expected output: the first call runs, later calls within the window are skipped

    Tracking the last run time and comparing against wait lets the first call through and blocks calls inside the window. apply forwards this and arguments so the original function behaves normally.

  4. Exercise 4Debug

    This debounce loses the arguments of the latest call. Find and fix the bug.

    starter.javascript
    function debounce(fn, wait) {
      let timer;
      return () => {
        clearTimeout(timer);
        timer = setTimeout(fn, wait);
      };
    }

    Reveal the reference answer
    reference.javascript
    function debounce(fn, wait) {
      let timer;
      return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), wait);
      };
    }

    Authored expected output: the last call's arguments are passed through

    The original passes fn directly to setTimeout, which calls it with no arguments and the wrong this. Capturing args and this in a closure and using apply forwards them to the latest call.

  5. Exercise 5Test

    Write assertions that prove a throttle runs the first call immediately and skips a call inside the window.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }

    Reveal the reference answer
    reference.javascript
    let calls = 0;
    const throttled = throttle(() => calls++, 1000);
    throttled();
    throttled();
    assertEqual(calls, 1, 'first call runs, second is inside the window');
    function throttle(fn, wait) {
      let last = 0;
      return function (...args) {
        const now = Date.now();
        if (now - last >= wait) { last = now; return fn.apply(this, args); }
      };
    }
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    The first call sets last to the current time and runs. The second call happens within the window, so the difference is below wait and the call is skipped.

  6. Exercise 6Interview

    How do you keep a debounced handler from firing after its component is gone?

    Reveal the reference answer
    reference.text
    I return a cancel function from the debounce and call it during cleanup, so any pending timer is cleared when the component unmounts or the effect re-runs. I also keep the timer id in the closure rather than on a shared object, and I use the framework's cleanup hook so cancellation is guaranteed. Without that, a stale callback can run against removed state and throw or leak.

    The answer should name a cancel method, cleanup timing and the stale-callback failure it prevents.

Common misconceptions

#
  • Debounce and throttle are interchangeable.
  • A debounced function runs on every event with a delay.
  • The wrapper does not need to forward this and arguments.

Follow-up practice

#
  • javascript-foundations-dom-and-events
  • javascript-foundations-fetch-and-network

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.