Debounce & Throttle
Tame wildly firing events. Learn how to use Debounce and Throttle to optimize performance and prevent your app from crashing under pressure.
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.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
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.