What is ts-debounce?
The ts-debounce npm package provides a simple and efficient way to debounce functions in TypeScript. Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, improving performance and user experience.
What are ts-debounce's main functionalities?
Basic Debounce
This feature allows you to debounce a function, ensuring it only executes after a specified delay. In this example, the `saveInput` function will only be called 300 milliseconds after the last input event.
const { debounce } = require('ts-debounce');
function saveInput() {
console.log('Saving data');
}
const debouncedSaveInput = debounce(saveInput, 300);
document.getElementById('input').addEventListener('input', debouncedSaveInput);
Debounce with Immediate Execution
This feature allows you to debounce a function but execute it immediately on the first call. Subsequent calls within the delay period will be ignored. In this example, `fetchData` will be called immediately on the first input event, and then debounced for 300 milliseconds.
const { debounce } = require('ts-debounce');
function fetchData() {
console.log('Fetching data');
}
const debouncedFetchData = debounce(fetchData, 300, { isImmediate: true });
document.getElementById('input').addEventListener('input', debouncedFetchData);
Cancel Debounce
This feature allows you to cancel a debounced function call. In this example, the `logMessage` function will be debounced for 300 milliseconds, but if the cancel button is clicked, the debounce will be cancelled.
const { debounce } = require('ts-debounce');
function logMessage() {
console.log('Logging message');
}
const debouncedLogMessage = debounce(logMessage, 300);
document.getElementById('input').addEventListener('input', debouncedLogMessage);
document.getElementById('cancelButton').addEventListener('click', () => {
debouncedLogMessage.cancel();
console.log('Debounce cancelled');
});
Other packages similar to ts-debounce
lodash.debounce
The lodash.debounce package provides similar functionality to ts-debounce, allowing you to debounce functions. It is part of the larger Lodash library, which offers a wide range of utility functions for JavaScript. Compared to ts-debounce, lodash.debounce is more widely used and has more features, but it also comes with the overhead of the entire Lodash library if not used selectively.
debounce
The debounce package is a lightweight alternative for debouncing functions. It offers similar functionality to ts-debounce but is more minimalistic. It is a good choice if you need a simple debounce solution without additional features or dependencies.
throttle-debounce
The throttle-debounce package provides both throttling and debouncing functionalities. It is a versatile library that can be used for both purposes, making it a good alternative to ts-debounce if you need both throttling and debouncing in your project.
TypeScript implementation of debounce 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
You can install this package using npm
using the command below
npm install ts-debounce
If you prefer yarn
, install using the command below
yarn add ts-debounce
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
then originalFunction
will be called immediately, but on subsequent calls of the debounced function original function won't be called, unless waitMilliseconds
passed after last call
maxWait
(number)
- if defined it will call the
originalFunction
after maxWait
time has passed, even if the debounced function is called in the meantime
- e.g. if
wait
is set to 100
and maxWait
to 200
, then if the debounced function is called every 50ms, then the original function will be called after 200ms anyway
callback
(function)
- it is called when
originalFunction
is debounced and receives as first parameter returned data from originalFunction
Cancellation
The returned debounced function can be cancelled by calling cancel()
on it.
const debouncedFunction = debounce(originalFunction, waitMilliseconds, options);
debouncedFunction.cancel();
Promises
Since v3 ts-debounce
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";
Credits & inspiration
This implementation is based upon following sources:
Compability
- version 3 - Promise must be available in the global namespace
- version 2 - TypeScript 3.3
- version 1 - TypeScript 2.0
Contributors ✨
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!