Lesson 3
Debounce & throttle
Build a practical mental model for debounce & throttle and use it in working JavaScript.
By the end, you will be able to…
- Explain debounce & throttle in your own words
- Use debounce & throttle in a small program
- Recognize and debug a common failure mode
Build the mental model
Debounce delays running a function until a burst of calls has paused for a set time, collapsing many rapid calls into one. Throttle instead guarantees a function runs at most once per fixed interval, no matter how often it's called.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
A search box firing an API request on every keystroke would overwhelm the server; debounce collapses that burst into one request after typing pauses.
Real-world example
Auto-save in a document editor is almost always debounced so it doesn't save on every single keystroke.
Common mistakes
- Reaching for throttle when debounce is what's needed, or vice versa
- Forgetting to clear the previous timer in a debounce implementation, causing every call to fire
- Debouncing something that needs an immediate response, like a button click
Try it yourself
Challenge
Implement throttle(fn, interval) that allows at most one call per interval.
Knowledge check
Which technique is best for a search-as-you-type input calling an API?
Summary
Debounce waits for a pause before running once; throttle guarantees at most one run per interval.