p-debounce-throttle v0.2.1
TypeScript implementation of debounce and throttle function
Debounce creates a new function g
, which when called will delay the invocation of the original function f
until n
milliseconds, BUT drop previous pending delayed emissions if a new invocation is made before n
milliseconds.
It's very useful for scenarios when it's better to limit the number of times the function is called. E.g. think of search input which fetches data from API. It's enough display search results after user has stopped entering characters for some time.
Install
npm i p-debounce-throttle -S
Function arguments
import { debounce } from "ts-debounce";
const debouncedFunction = debounce(originalFunction, waitMilliseconds, options);
originalFunction
- the function which we want to debounce
waitMilliseconds
- how many seconds must pass after most recent function call, for the original function to be called
options
isImmediate
(boolean)- if set to
true
thenoriginalFunction
will be called immediately, but on subsequent calls of the debounced function original function won't be called, unlesswaitMilliseconds
passed after last call
- if set to
maxWait
(number)- if defined it will call the
originalFunction
aftermaxWait
time has passed, even if the debounced function is called in the meantime- e.g. if
wait
is set to100
andmaxWait
to200
, then if the debounced function is called every 50ms, then the original function will be called after 200ms anyway
- e.g. if
- if defined it will call the
callback
(function)- it is called when
originalFunction
is debounced and receives as first parameter returned data fromoriginalFunction
- it is called when
Cancellation
The returned debounced function can be cancelled by calling cancel()
on it.
const debouncedFunction = debounce(originalFunction, waitMilliseconds, options);
debouncedFunction.cancel();
Promises
ts-debounce-throttle
has Promise support. Everytime you call debounced function a promise is returned which will be resolved when the original function will be finally called. This promise will be rejected, if the debounced function will be cancelled.
You can also debounce a function f
which returns a promise. The returned promise(s) will resolve (unless cancelled) with the return value of the original function.
const asyncFunction = async () => "value";
const g = debounce(asyncFunction);
const returnValue = await g();
returnValue === "value"; // true
Credits & inspiration
This implementation is based upon following sources:
- JavaScript Debounce Function by David Walsh
- Lodash implementation
- p-debounce