Track 02 · Lesson 8 of 17Inside the browser

Track 02 · Inside the browser

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 keystroke

Which 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.
  • requestAnimationFrame for 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

A search box should call the API only after the user stops typing. Which technique fits?