Debounce vs Throttle in JavaScript: Simple Guide + Code

Debounce vs Throttle in JavaScript: Complete Comparison + Code

Featured Snippet

Debounce and throttle are two handy JavaScript techniques that help control how often a function runs when dealing with rapid-fire events like scroll, resize, or keypress. Debounce waits for the event to settle before firing, while throttle ensures a function runs at fixed intervals. Both improve performance and prevent unnecessary calls.

Table of Contents

What Are High-Frequency Events?

If you’ve ever attached a scroll or mousemove listener and logged inside it, you know the pain. The console explodes with logs. The browser fans spin like a jet engine. These events fire dozens—sometimes hundreds—of times per second.

I once crashed Chrome during a hackathon because my scroll handler was doing way too much. Lesson learned.

To tame this chaos, we rely on debounce and throttle.

What Is Debouncing?

Debouncing ensures a function runs only after the event stops firing for a certain delay. It’s like waiting for a user to stop typing before fetching search results.

How Debounce Works Internally

  1. Start a timer every time the event fires.
  2. If the event fires again, reset the timer.
  3. When the timer finishes, execute the function.

Debounce Code Example


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

// Example: search input
const searchHandler = debounce((e) => {
  console.log("Searching for:", e.target.value);
}, 500);

document.getElementById("search").addEventListener("keyup", searchHandler);

When Should You Use Debounce?

Use debounce when you want to react to a user’s final input, not every keystroke.

  • Search boxes
  • Auto-saving inputs
  • Window resize end detection
  • Form validation
  • Preventing double-clicks

What Is Throttling?

Throttle executes a function at fixed intervals, no matter how many times the event fires.

How Throttle Works Internally

1. Timestamp-based Throttle

Check execution time and run only when enough time has passed.

2. Timer-based Throttle

Start a timer, ignore further events until timer ends.

I prefer timer-based throttling—it’s easier to think about.

Throttle Code Example


function throttle(fn, limit) {
  let waiting = false;
  return function(...args) {
    if (!waiting) {
      fn.apply(this, args);
      waiting = true;
      setTimeout(() => {
        waiting = false;
      }, limit);
    }
  };
}

// Example: Infinite scroll handler
const handleScroll = throttle(() => {
  console.log("Scroll event at", Date.now());
}, 200);

document.addEventListener("scroll", handleScroll);

When Should You Use Throttle?

Use throttle when you need periodic updates.

  • Scroll events
  • Drag-and-drop updates
  • Live UI resizing
  • Analytics pings
  • Preventing rapid-fire event triggers

Debounce vs Throttle: Key Differences

FeatureDebounceThrottle
Execution timingRuns after event stopsRuns at fixed intervals
FrequencyMinimum possible callsPredictable call rate
Best forSearch, validationScroll, drag, analytics
BehaviorWait for silenceRegulate frequency

Simple rule: If you care about the final action → debounce.
If you care about continuous updates → throttle.

Performance Considerations

1. UI Smoothness

Throttle ensures periodic UI updates; debounce might feel laggy for animations.

2. API Load

Debounce drastically reduces unnecessary API calls.

3. Memory Use

Both use closures and timers—modern JS handles this well.

4. Avoid Function Recreation

Define debounce/throttle once and reuse.

Best Practices

  • Use 100–300ms delay for typical UI tasks.
  • Don’t debounce animations.
  • Don’t throttle text inputs.
  • Debounce for search.
  • Throttle for scroll.

Frequently Asked Questions (FAQ)

1. Can debounce and throttle be used together?

Yes, you can debounce API calls inside a throttled scroll listener.

2. Is debounce better for API requests?

Usually yes—debounce respects final user intent.

3. Does React have built-in debounce?

No, but Lodash and custom hooks provide it easily.

4. Should window resize be debounced?

Yes, unless you want live feedback.

5. Are debounce and throttle mobile-friendly?

Yes, they reduce CPU load and help battery life.

Leave a Comment

Your email address will not be published. Required fields are marked *