CodeBlanks Logo Icon CodeBlanks

Debounce

JavaScript course · Expert · Lesson 9/63

Learn to delay a frequently-fired event with debounce.

Debounce

Debounce waits for a pause in a rapidly fired event before running the handler. Each trigger cancels the previous timer and starts a new one.

For example, in a search box you can avoid running a query on every keystroke and instead run a single query once the user stops typing. This reduces unnecessary network requests.

Exercise Debounce function

Write a function named debounce. It takes fn and delay and returns a wrapper that delays the call with a timer. Each call should clear the previous timer with clearTimeout.

Show example solution
Keep a timer variable; on each call clearTimeout(timer) then setTimeout.

Example solution:
function debounce(fn, delay) {
  let timer = null;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

Where to debounce?

Debounce is most common in search boxes, window resizing, and form validation — anywhere you want to wait until the user pauses. A typical delay is 200–400 ms.

Too short and unnecessary calls still slip through; too long and the interface feels sluggish. Pick the value that fits your scenario.

Test yourself

  1. What happens each time a debounced function is triggered?

    • The previous timer is cleared and a new one starts
    • It runs and finishes immediately
    • It never runs
    • It runs twice each time
    Show answer

    The previous timer is cleared and a new one starts — Correct! Each trigger clears the previous timer and starts a new wait.

  2. Debounce skeleton

    clearTimeout(____);
    timer = setTimeout(() => fn(...args), delay);
    Show answer
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  3. Match the debounce terms

    setTimeout
    delayed call
    clearTimeout
    cancel timer
    trailing call
    last call runs
    delay
    wait duration

All lessons in Expert