Lodash Debounce Configuration Options Guide
The _.debounce method in the Lodash JavaScript library
limits the rate at which a function can fire, making it essential for
handling events like scrolling, resizing, and rapid user input. Beyond
setting a simple delay in milliseconds, Lodash allows you to fine-tune
execution behavior by passing an optional configuration object as the
third argument: _.debounce(func, [wait=0], [options={}]).
This article covers the specific options you can pass to configure
_.debounce—namely leading,
maxWait, and trailing—to control precisely
when your debounced function executes.
The options Object
The third parameter of _.debounce accepts an object with
three optional properties:
const debouncedFunction = _.debounce(calculateLayout, 300, {
leading: false,
maxWait: 1000,
trailing: true
});1. leading (boolean)
- Default:
false - Description: Determines whether the function is
invoked on the leading edge of the timeout. When set to
true, the debounced function executes immediately on the very first call. If additional calls occur within the specifiedwaitperiod, they will be delayed according to the debouncing logic.
2. trailing (boolean)
- Default:
true - Description: Determines whether the function is
invoked on the trailing edge of the timeout. When set to
true, the debounced function will run after thewaittime has elapsed since the last call was made. If bothleadingandtrailingare set totrue, the function runs at the start of the burst and again at the end (provided it was called more than once during the interval).
3. maxWait (number)
- Default:
undefined - Description: Defines the maximum time (in milliseconds) the debounced function is allowed to be delayed before it is forcibly executed. This prevents a continuously triggered event (such as infinite scrolling or nonstop typing) from postponing function execution indefinitely.
Common Configuration Scenarios
Immediate Execution (Leading Only):
To execute an action immediately and block subsequent calls until user activity pauses:_.debounce(submitForm, 500, { leading: true, trailing: false });Guaranteed Execution (Using
maxWait):
To debounce search queries while ensuring results update periodically even if the user does not stop typing:_.debounce(fetchSearchResults, 300, { maxWait: 1000 });Both Edges Triggered:
To capture the initial state immediately and also ensure the final state is captured after interactions cease:_.debounce(syncData, 400, { leading: true, trailing: true });