Track 02 · Lesson 8 of 17Inside the browser
- 01Events and bubbling
- 02What fires when you click or type
- 03Keyboard, input and focus events
- 04Default actions and preventDefault()
- 05Event delegation
- 06Listener options and cleanup
- 07Custom events
- 08Debounce and throttle
- 09Events in React
- 10The event loop
- 11Don't block the main thread
- 12The rendering pipeline
- 13Core Web Vitals
- 14HTTP caching
- 15Responsive design
- 16SEO basics
- 17Service workers and offline
Debounce and throttle
Lesson 8 of 17· 6 min
Some events fire far more often than you need: every keystroke, every pixel of scrolling. Debounce waits until the events stop; throttle lets one through at most every so often. Type in the search box with each mode and compare the requests.
Count the requests
Type fast, then pause
0
keystrokes
0
requests sent
0%
requests saved
// Requests will appear here
input.addEventListener("input", (e) => search(e.target.value));
// One request per keystrokeWhich one when#
- Debounce when only the final value matters: search boxes, autosave, "the window has finished resizing".
- Throttle when you want steady updates while something is happening: scroll position, mouse tracking, dragging.
requestAnimationFramefor visual updates during scrolling or dragging: it runs exactly once per frame, which is the most the screen can show anyway.
The React catch#
In React, a debounced function created inside a component is recreated on every render, and each copy has its own timer, so nothing gets debounced. Keep it stable with useMemo or useRef, or use a library hook, and cancel the pending call when the component unmounts.
Check yourself