Confused about the maxWait option for LoDash's debounce method

If you look at the source code, you will find that throttle actually is a thin wrapper for debounce. Throttle calls debounce using the maxWait property https://github.com/lodash/lodash/blob/4.17.11/lodash.js#L10898-L10914

So if you call debounce with maxWait and trailing and leading set to true, it will have the same effect as calling throttle.


They are a similar concept but quite different.

maxWait - the amount of time to wait before the function is called.

throttle - the amount of time to wait between calls.

throttle is used when you are calling a function multiple times and don't want it to be called too often. maxWait is used when you are delaying execution of a single event.

edit adding a bit more detail here:

the difference between _throttle and _debounce is a bit subtle.

_debounce creates a function which:

Creates a function that will delay the execution of func until after wait milliseconds have elapsed since the last time it was invoked.

while _throttle creates a function which:

Creates a function that, when executed, will only call the func function at most once per every wait milliseconds.

_debounce actually allows subsequent calls to occur, but delays their processing, while _throttle actually disallows calls during the wait period.

You can debounce a function multiple times, delaying it theoretically indefinitely. maxWait can be used to ensure the function does eventually get called.

The leading and trailing options do not cause additional runs of the function; instead, they control when the function is executed.

Using leading causes the function to execute, and subsequent calls to be debounced.

Using trailing causes the function to execute at the end of the debounce, which could be less than the timeout. Essentially, you are allowing the subsequent calls to happen as soon as the last debounce time ends, instead of forcing them to wait for their entire timeout if they started in the middle.

Note: If leading and trailing options are true func will be called on the trailing edge of the timeout only if the the debounced function is invoked more than once during the wait timeout.

so, in theory if you used all 3 options (leading, maxWait, and trailing), the maxWait wouldn't happen because you would never exceed the wait period, and trailing would only happen if you called the function twice in the same wait period.