Sub topic 13
Using Lodash debounce and throttle in Production
The earlier chapters built debounce and throttle by hand. That taught you how they work, but hand-written versions tend to miss edge cases: timer drift, a maxWait that is shorter than wait, return values, and combinations of options that interact in surprising ways. Lodash ships implementations that have handled these cases for years. This chapter shows how to use them, what each option really does, and where they still catch people out.
This chapter assumes you are comfortable with the trailing and leading debounce, the timestamp throttle, cancel/flush, and maxWait from earlier chapters, and that you can run Node.js scripts with an npm package installed.
Installing and Importing
Install the main package:
npm install lodashHow you import it affects bundle size. Each import style behaves differently:
| Import style | Example | Bundle impact |
|---|---|---|
| Whole library | `import _ from 'lodash'` | Pulls in all of Lodash (about 70 KB minified) unless your bundler is configured otherwise |
| Per-method path | `import debounce from 'lodash/debounce'` | Only `debounce` and its small internal helpers |
| ES module build | `import { debounce } from 'lodash-es'` | Tree-shakable with modern bundlers |
| Standalone package | `import debounce from 'lodash.debounce'` | Works, but these packages are no longer maintained in step with the main library |
Use the per-method path or lodash-es. Avoid the standalone lodash.debounce style packages in new code.
The Signatures
Both functions take a function, a wait in milliseconds, and an options object:
debounce(func, wait = 0, { leading = false, trailing = true, maxWait })
throttle(func, wait = 0, { leading = true, trailing = true })Both return a wrapped function that has cancel() and flush() methods, the same controls you built by hand. The wrapper passes on this and the latest arguments, as your versions did.
The defaults differ, and that difference is easy to miss. A debounce fires only on the trailing edge by default. A throttle fires on both edges by default.
How the Options Combine for debounce
Run this script with Node to see the leading and trailing edges together:
const debounce = require('lodash/debounce');
const start = Date.now();
const log = (msg) => console.log(`${String(Date.now() - start).padStart(4)} ms ${msg}`);
const handler = debounce((value) => log(`handler ran with ${value}`), 100, {
leading: true,
trailing: true,
});
handler('a'); // t=0: leading call runs immediately
setTimeout(() => handler('b'), 30); // inside the wait: deferred
setTimeout(() => handler('c'), 60); // inside the wait: replaces 'b'
// trailing call runs about 100 ms after the last call, with 'c'
setTimeout(() => handler('solo'), 400); // new burst with a single call
// only the leading call runs for this burstTypical output:
0 ms handler ran with a
161 ms handler ran with c
400 ms handler ran with soloThe last burst shows a rule that surprises many people. When both leading and trailing are true, Lodash runs the trailing call only if the wrapper was called more than once during the wait. A single isolated call runs once, on the leading edge, not twice.
This table lists every combination:
| leading | trailing | Behavior during a burst |
|---|---|---|
| `false` | `true` | One call, `wait` ms after the last event (default) |
| `true` | `false` | One call at the start; later calls ignored until a quiet `wait` period passes |
| `true` | `true` | Call at the start, plus one at the end if more calls came in |
| `false` | `false` | Never runs. Lodash accepts this silently |
maxWait in Practice
maxWait caps how long a call can be postponed while events keep arriving. That makes debounce useful for autosave: you want to save soon after the user pauses, but you also want to save during long typing sessions.
const debounce = require('lodash/debounce');
const start = Date.now();
let n = 0;
const save = debounce((count) => {
console.log(`${Date.now() - start} ms saved at keystroke ${count}`);
}, 200, { maxWait: 500 });
const typing = setInterval(() => save(++n), 50); // a keystroke every 50 ms
setTimeout(() => clearInterval(typing), 1200); // user stops at ~1.2 sThe keystrokes never pause for 200 ms, so without maxWait there would be a single save at about 1400 ms. With maxWait: 500 you get saves at roughly 550 ms and 1050 ms, and then a final trailing save about 200 ms after the last keystroke.
Two details matter here:
- If you pass a
maxWaitsmaller thanwait, Lodash raises it towait. You cannot usemaxWaitto make a debounce fire sooner than its own wait. - Lodash's
throttleis built ondebounce. Internally it callsdebounce(func, wait, { leading, trailing, maxWait: wait }). A throttle is a debounce that is never allowed to wait longer than one interval.
throttle Options
For throttle, the defaults (leading: true, trailing: true) suit most UI work. The first scroll or resize event gets an immediate response, and the final position is always handled.
import throttle from 'lodash/throttle';
const onResize = throttle(() => {
console.log('Width:', window.innerWidth);
}, 250, { leading: true, trailing: true });
window.addEventListener('resize', onResize);Set trailing: false only when the final event truly does not matter, for example rate-limiting a "fire" button in a game, where an extra shot after the user lets go would be a bug. Set leading: false when you want the first response delayed by one interval, which is rare.
Return Values Are Stale
Lodash's wrappers return the result of the most recent actual invocation of func, not the result of the call you just made:
const debounce = require('lodash/debounce');
const double = debounce((x) => x * 2, 100);
console.log(double(1)); // undefined: nothing has run yet
setTimeout(() => {
console.log(double(5)); // 2: result from the earlier call with 1, not 10
}, 200);Do not rely on the return value of a debounced or throttled function. If you need the result, have func write it somewhere, such as state, a callback, or a resolved promise. flush() is the exception: it runs any pending call synchronously and returns that call's result.
cancel and flush in Real Code
The two methods map directly to lifecycle events:
cancel()drops any pending call. Use it when the thing the call would update is gone: a component unmounted, a dialog closed, a route changed.flush()runs a pending call now. Use it when you are about to lose the chance to run it later.
import debounce from 'lodash/debounce';
const saveDraft = debounce(() => {
localStorage.setItem('draft', document.querySelector('#editor').value);
}, 1000, { maxWait: 5000 });
document.querySelector('#editor').addEventListener('input', saveDraft);
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') saveDraft.flush();
});Production Gotchas
Creating a New Wrapper on Every Call
Each call to debounce() creates a new, independent timer. This code does not debounce anything:
// Wrong: a fresh debounced function per event, so every event fires
input.addEventListener('input', (e) => {
debounce(() => search(e.target.value), 300)();
});Create the wrapper once and reuse it. In frameworks that re-run component code, this means memoizing the wrapper, which the next chapter covers for React.
Removing Listeners
removeEventListener needs the same function reference you added. Keep the wrapped function in a variable and pass that variable to both calls. Call cancel() as well when you remove it, or a pending trailing call can still fire after the listener is gone.
Fake Timers and Date.now
Lodash reads Date.now() to measure elapsed time, as well as using setTimeout. Jest's modern fake timers (the default since Jest 27) mock both, so jest.advanceTimersByTime() works with Lodash. The legacy fake timers mocked only the timer functions, and Lodash wrappers would appear to hang or fire at the wrong time. If an older test suite uses jest.useFakeTimers('legacy') or a custom timer stub, that is the likely cause.
Background Tabs
Browsers clamp timers in background tabs, often to once per second or slower. A 200 ms throttle can turn into a 1000 ms or longer throttle while the tab is hidden. Lodash cannot prevent this. Do not use a throttle for logic that depends on exact timing.
Lodash or Your Own?
| Situation | Recommendation |
|---|---|
| Lodash is already a dependency | Use `lodash/debounce` and `lodash/throttle` |
| You need `maxWait`, both edges, `flush` return values | Use Lodash; these are where hand-written versions break |
| A tiny library with zero dependencies | A short hand-written trailing debounce is reasonable |
| Visual updates tied to rendering | Use the `requestAnimationFrame` throttle from the earlier chapter, not a millisecond wait |
Exercise
You configure debounce(fn, 300, { leading: true, trailing: true }) and the user clicks a button exactly once, then does nothing. How many times does fn run, and why?
Show answer
Once, on the leading edge. When both edges are enabled, Lodash runs the trailing call only if the debounced function was called more than once during the wait. One isolated call produces only the leading invocation.
Exercise
A teammate writes debounce(save, 1000, { maxWait: 300 }) hoping saves happen at least every 300 ms during typing. What actually happens?
Show answer
Lodash raises maxWait to the value of wait, so the effective maxWait is 1000 ms. During continuous typing, saves happen about once per second, not every 300 ms. To save more often, lower wait or use throttle(save, 300).
Exercise
A search handler does const results = debouncedSearch(query); render(results); and the screen always shows results for an older query. Explain the bug and fix it.
Show answer
Lodash wrappers return the result of the last invocation that actually ran, not the current call, so results always belongs to an earlier query (or is undefined at first). Move rendering into the debounced function itself, for example debounce((q) => render(search(q)), 300), or have it update state that the UI reads.
Exercise
Which option combination makes a Lodash throttle never call its function, and does Lodash warn you?
Show answer
{ leading: false, trailing: false }. Lodash accepts it silently, without an error or warning, and the function never runs.