Sub topic 13
Using Lodash debounce and throttle in Production
This chapter assumes you have built your own debounce and throttle, and that you understand leading and trailing edges, cancel and flush, and maxWait from earlier chapters. It also assumes you can install npm packages and use either import or require.
Hand-written helpers are good for learning. In production, Lodash's versions are a safer default. They have years of bug fixes behind them for timer edge cases, they return the last result, and they share one consistent set of options.
Importing Only What You Need
Lodash is large, so import single functions rather than the whole library:
// Per-method paths (CommonJS or ESM via bundler)
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';
// Or, for native ES modules and tree shaking:
// import { debounce, throttle } from 'lodash-es';A plain import _ from 'lodash' pulls in the full library, and most bundlers cannot shrink it.
The Options
| Option | `debounce` default | `throttle` default | Effect |
|---|---|---|---|
| `leading` | `false` | `true` | Call on the first invocation of a burst |
| `trailing` | `true` | `true` | Call once more after the burst, with the latest arguments |
| `maxWait` | none | equals `wait` | Longest time a call can be delayed |
Both wrapped functions have .cancel() and .flush(). A call to the wrapper returns the result of the most recent invocation of fn. For a trailing-only debounce, that means the previous call's result, or undefined the first time.
Throttle Is Debounce with maxWait
Lodash implements throttle(fn, wait, opts) as debounce(fn, wait, { leading, trailing, maxWait: wait }). Knowing this explains its behavior. A debounce whose delay can never go past wait fires at most once per wait during continuous activity, and that is what a throttle does.
A Runnable Example
Save this as demo.js, run npm install lodash, then run node demo.js:
const debounce = require('lodash/debounce');
const throttle = require('lodash/throttle');
const start = Date.now();
const log = (label) => (value) =>
console.log(`${label} ${value} at ~${Date.now() - start}ms`);
// Fires on the first call and again after the burst ends.
const both = debounce(log('debounce'), 100, { leading: true, trailing: true });
both(1);
both(2);
both(3);
// Saves at most every 500 ms while calls keep arriving.
const autosave = debounce(log('autosave'), 200, { maxWait: 500 });
const interval = setInterval(() => autosave('draft'), 50);
setTimeout(() => clearInterval(interval), 1200);
// Throttle without the trailing call.
const leadOnly = throttle(log('throttle'), 300, { trailing: false });
leadOnly('a');
leadOnly('b'); // dropped
setTimeout(() => leadOnly('c'), 350); // runs: window has passedExpected output: debounce 1 right away, then debounce 3 at about 100 ms. Autosave logs at about 500 ms and 1000 ms, then one last time about 200 ms after the interval stops. The throttle logs a, then c.
Production Patterns
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';
const saveDraft = debounce(() => {
console.log('Saving draft');
}, 1000, { maxWait: 5000 });
const onResize = throttle(() => {
console.log('Width:', window.innerWidth);
}, 250, { leading: true, trailing: true });
window.addEventListener('resize', onResize);
window.addEventListener('beforeunload', () => saveDraft.flush());Keep a reference to each wrapper. You need the same reference later for removeEventListener, cancel, and flush.
Common Mistakes
- Wrapping inline.
el.addEventListener('input', debounce(fn, 300))works, but you can never remove that listener or cancel its timer. - Creating a new wrapper on every call. Code like
() => debounce(fn, 300)()makes a fresh timer each time, so nothing gets debounced. - Setting
leading: falseandtrailing: false. The function never runs. - Setting
maxWaitbelowwait. Lodash raisesmaxWaittowait, so the setting has no effect. - Forgetting cleanup. Call
.cancel()when the owning view is torn down. Otherwise a pending call can run against stale state.
Exercise
You want a search box to send a request as soon as the user starts typing, then once more with the final text, and never wait longer than 1 second between requests while they type. Write the Lodash call.
Show answer
debounce(search, 300, { leading: true, trailing: true, maxWait: 1000 }). leading sends the first request right away, trailing sends the final text, and maxWait forces a request at least every 1000 ms during continuous typing.
Exercise
Why does throttle(fn, 200) with default options behave the same as debounce(fn, 200, { leading: true, maxWait: 200 })?
Show answer
Lodash implements throttle as a debounce with maxWait equal to wait. Its leading and trailing defaults are both true, and debounce's trailing default is already true, so both calls set up the same configuration.