Lodash _.debounce() method
What you’ll learn
- How debounce delays expensive work until input events settle.
- How
leading,trailing, andmaxWaitaffect scheduling. - When to call
cancel()andflush()in real UI lifecycles. - How it differs from
_.throttlefor continuous streams.
Prerequisites
Recommended: _.curryRight() for wrapper basics and the Function hub for timing context.
- Event loops: knowing that timers run later, not inline.
- UI cleanup: cancel pending handlers on unmount/navigation.
Overview
_.debounce(func, wait, options) returns a wrapper that waits for inactivity before invoking func. It tracks the latest arguments, supports leading/trailing edge control, and exposes cancel() and flush().
Syntax
_.debounce(func, [wait=0], [options])- func: callback to debounce.
- wait: milliseconds to wait after the last call.
- options:
leading,trailing, and optionalmaxWait. - returns: debounced function with
cancelandflushmethods.
Default trailing debounce
Three rapid calls run func once after the wait window.
import debounce from "lodash/debounce";
let runs = 0;
const save = debounce(() => { runs += 1; }, 120);
save();
save();
save();
setTimeout(() => console.log(runs), 160);
// 1Leading only
With { leading: true, trailing: false }, first call in a burst runs immediately.
import debounce from "lodash/debounce";
let runs = 0;
const clickOnce = debounce(() => { runs += 1; }, 200, {
leading: true,
trailing: false
});
clickOnce();
clickOnce();
clickOnce();
console.log(runs);
// 1cancel() and flush()
Cancel prevents pending trailing execution; flush runs it immediately.
import debounce from "lodash/debounce";
const log = [];
const push = debounce((v) => log.push(v), 300);
push("A");
push.cancel(); // A never runs
push("B");
push.flush(); // runs now
console.log(log);
// ["B"]📋 _.debounce vs _.throttle
| Helper | Best for | Behavior |
|---|---|---|
_.debounce | Search input, autosave | Wait for quiet period |
_.throttle | Scroll/resize streams | Run at most once per interval |
Pitfalls to avoid
Forgotten cancel
Pending handlers can run after component teardown unless cancelled.
leading + trailing confusion
Trailing with both true only fires if the wrapper is called multiple times during wait.
No periodic updates
Use maxWait when constant events must still emit at intervals.
❓ FAQ
Summary
- Purpose: debounce delays work until calls stop for a configured interval.
- Controls: leading/trailing/maxWait plus
cancel()andflush(). - Next: Lodash _.defer() or compare with _.throttle().
Lodash stores the latest arguments and returns the last invocation result from the debounced wrapper; with both leading and trailing enabled, trailing fires only when the wrapper is called more than once during the wait window.
6 people found this page helpful
