The function to debounce.
How long to wait before calling the function after the last call. Defaults to 0
Optional
index?: TQueued extends true ? number | ((...args: Parameters<T>) => number) : undefinedThe index number of the argument that will be used as the key to the queues if queues are enabled.
Optional
leading?: booleanWhether the first call is called immediately, and all subsequent calls ignored, defaults to false. Note that if trailing and leading are both set to true, trailing will only fire if there were multiple calls before the wait period timed out.
Optional
promisify?: TPromisifyWhether to promisify the debounced function.
Optional
queue?: DebounceQueue | TQueuedWhether to use queues, or a queues object to use.
Optional
trailing?: booleanWhether the call is delayed until the end of the timeout. Defaults to true.
Returns a debounced function.
Has all the typical options (e.g. trailing, leading) for a debounce function and the ability to cancel/flush the debounced funciton.
AND it can also create debounced queues.
Debounced Queues
What are they?
Queues allow you to avoid creating a debounce function for every instance that needs to debounce the same function.
For example, say you want to debounce the saving of notes to a database until after a user stops typing. For each note open you would have to create a debounced version of the save function, and usually, when using frameworks, this would happen at the component level, not the store because the store save function is shared.
Queues would allow you to avoid all that, and keep all the saving logic at the store level, allowing components to just call save normally.
Options
Queues
To use queues, either pass
{ queues: true }
or{ queues: {} }
. You can also have multiple debounced functions share a queue (e.g. save and delete):Index
Internally the queues object looks like this, where
key
is one of the arguments passed to the function (e.g. a note's id), by default the first, and it deletes the key after a function is finally called:So the following would debounce the callback based on the id the function was called with:
If you need to debounce based on something more complicated (a property of an argument or multiple arguments) index can be a function that returns the key to use.
Promisified Debounce
The function also supports wrapping async by passing
{promisify: true}
. We must tell the function whether to promisify since we can't/shouldn't deferentiate between regular and async function.When promisify is enabled, when the funciton is debounced, the callback will be called with
Error("Debounced")
as the first param. This is so that when awaiting you can tell whether the result is a real result, or just the debounce.You can check what type of result it is with the isDebouncedResult utilty funciton.