Debounce & Throttle

Tame wildly firing events. Learn how to use Debounce and Throttle to optimize performance and prevent your app from crashing under pressure.

JavaScript6 min readConcept 55 of 63

Rate Limiting Functions

DOM events like scrolling, resizing, or typing can fire dozens of times per second. If you attach heavy logic (like an API call) to these events, you will freeze the browser or overload your server.

**Debounce** and **Throttle** are two higher-order functions that control *how often* a given function is allowed to execute.

The Difference

**Debounce**: 'Wait until the user stops doing the thing.' It resets its timer every time the event fires. The function only executes after a period of total silence.

**Throttle**: 'Do the thing, but no more than once every X milliseconds.' It enforces a strict speed limit. Even if the event fires 100 times in one second, a 1-second throttle will only execute the function 1 time.

When to use which?

- **Search Inputs (Debounce)**: You don't want to make an API call for every keystroke (a, ap, app, appl, apple). You want to wait until the user *stops* typing for 300ms, and then make one API call for apple.

- **Scroll Events (Throttle)**: If you are animating elements as the user scrolls, waiting for them to stop scrolling (debounce) would look broken. You want the animation to update continuously, but capped at 60 frames per second (throttle) to save CPU.

The Event Spammer

Spam the button below as fast as you can. Watch how the Raw count skyrockets, while Throttle enforces a strict rhythm, and Debounce patiently waits for you to tire out.

Raw Event
0
Debounce
0
Resets on every click
Throttle
0
Caps at 1 execution / sec
iWatch the progress bars carefully. The Debounce bar gets ruthlessly reset to 100% every single time you click. It only reaches 0% (and increments) if you take your hands off the mouse.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1You are building an auto-saving text editor. Which technique should you use to save the document to the database?
  2. 2How does Debounce actually work under the hood?
  3. 3You are building a 'infinite scroll' feed that fetches more posts as the user scrolls near the bottom. Which technique is best?

Remember this

  • DOM events (scroll, resize, keyup) can fire too rapidly for heavy logic to handle.
  • **Debounce** groups a rapid series of events into a single execution, firing only after a period of silence.
  • Use Debounce for search inputs and auto-saving.
  • **Throttle** guarantees a function runs at a consistent, capped rate over time.
  • Use Throttle for scroll listeners, resize listeners, and rapid-fire button clicks.
  • Under the hood, both rely on closures to maintain state (like timer IDs or last execution timestamps).

Done with this concept?

Mark it complete to track your progress. No login needed.