High-frequency DOM events—such as scroll, resize, mousemove, and input—can fire hundreds of times per second. Attaching computationally heavy functions (DOM updates, API calls) directly to these events causes severe UI lag and layout thrashing. Debouncing and Throttling are rate-limiting techniques that govern how frequently a function executes.
| Technique | Core Behavior | Ideal Use Cases |
|---|---|---|
| Debounce | Delays execution until a period of inactivity has elapsed | Auto-complete search inputs, auto-saving form drafts |
| Throttle | Enforces a maximum execution rate (once per $N$ milliseconds) | Scroll position trackers, games, infinite scroll triggers |
A robust debounce implementation supports both trailing (default) and immediate leading-edge execution:
Enforces execution at most once every limit milliseconds using timestamps:
For visual updates (dragging elements, canvas drawing), throttling via requestAnimationFrame syncs execution directly with the monitor's refresh rate (60Hz / 120Hz):
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Custom Events & Event Dispatching | Passive Event Listeners & Touch Optimization |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.