# Debounce & Throttle

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

Subject: JavaScript | Lesson 55 of 63 | 6 min read
Interactive lesson: https://codewithanimation.in/javascript/debounce-throttle
Previous: [Dates, Time & Intl](https://codewithanimation.in/javascript/dates-and-time.md) | Next: [Memoization & Currying](https://codewithanimation.in/javascript/memoization-and-currying.md)

## 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.

## Common mistake: Memory Leaks via Timers

Both patterns rely heavily on `setTimeout`. If a component unmounts while a debounced function is still waiting in its 'quiet period', it will fire on a component that no longer exists, causing a memory leak or a React state error.

Always ensure you can `cancel()` or clear the underlying timeout when the component is destroyed.

## Tip: Lodash to the rescue

While it is a great exercise to write your own `debounce()` and `throttle()` functions using closures, in production apps it is highly recommended to use a battle-tested library like Lodash (`_.debounce` and `_.throttle`) which perfectly handles edge cases like trailing and leading executions.

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/debounce-throttle

## Check yourself

### Question 1

You are building an auto-saving text editor. Which technique should you use to save the document to the database?

- A. Debounce: Save only after the user stops typing for 1 second.
- B. Throttle: Save exactly every 1 second while they are typing.
- C. Raw: Save on every single keystroke.

Correct answer: A

Debounce is perfect for auto-save. It waits for the user to pause their train of thought, and then efficiently saves the entire chunk of work in a single API call.

- Why not B: Incorrect. Throttling would result in too many unnecessary database calls if they are just typing a long sentence continuously.
- Why not C: Incorrect. This would DDoD your database.

### Question 2

How does Debounce actually work under the hood?

- A. It uses `setTimeout`. If the event fires again before the timeout finishes, it calls `clearTimeout` and starts the timer over from zero.
- B. It uses `setInterval` to check a boolean flag every 100ms.
- C. It forces the JavaScript thread to sleep using a `while` loop.

Correct answer: A

Debounce relies on closures to remember the `timerId`. Every time the function is called, it clears the previous timer and sets a brand new one, pushing the execution further into the future.

- Why not B: Incorrect. It relies on resetting timeouts, not polling intervals.
- Why not C: Incorrect. Blocking the main thread freezes the entire browser.

### Question 3

You are building a 'infinite scroll' feed that fetches more posts as the user scrolls near the bottom. Which technique is best?

- A. Throttle
- B. Debounce
- C. Raw Event

Correct answer: A

Throttle ensures that as the user is actively scrolling down, you check their position at a reasonable, capped rate (e.g., every 200ms) and trigger the fetch *while* they are moving.

- Why not B: Incorrect. Debounce would only trigger *after* they stop scrolling, which means they'd hit the bottom, stop, and *then* the posts would load. Not a good UX.
- Why not C: Incorrect. The scroll event fires dozens of times per second. You'd trigger the 'fetch more' API call dozens of times instantly.

## 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).
