debounce-throttle-ts v1.0.0
debounce-throttle-ts
A TypeScript package that implements debounce and throttle functions for optimizing performance in scenarios such as event handling, API calls, and more.
Features
- Debounce: Ensures a function is executed only after a specified delay, useful for preventing excessive function calls (e.g., in search input or resize events).
- Throttle: Ensures a function is executed at a fixed rate, useful for limiting the number of times a function can be called over time (e.g., scroll or mousemove events).
Installation
To install the package, run the following command:
npm install debounce-throttle-ts
Development Installation
If you're working on the development of the package, you can install the dependencies with:
npm install
Usage
Debounce Example
The debounce
function creates a debounced version of the provided function. The debounced function will only execute after the specified delay has passed since the last invocation.
import { debounce } from 'debounce-throttle-ts';
// Example function to be debounced
const logMessage = (message: string) => {
console.log(message);
};
// Create a debounced version of logMessage with a 1000ms delay
const debouncedLog = debounce(logMessage, 1000);
// Call debounced function multiple times
debouncedLog('Debounce 1');
debouncedLog('Debounce 2');
debouncedLog('Debounce 3'); // Only this one will be logged after 1 second
Throttle Example
The throttle
function creates a throttled version of the provided function. The throttled function will only execute at most once every limit
milliseconds.
import { throttle } from 'debounce-throttle-ts';
// Example function to be throttled
const logMessage = (message: string) => {
console.log(message);
};
// Create a throttled version of logMessage with a 2000ms limit
const throttledLog = throttle(logMessage, 2000);
// Call throttled function multiple times
throttledLog('Throttle 1');
throttledLog('Throttle 2');
throttledLog('Throttle 3'); // Only the first and third logs will happen, 2 seconds apart
Development
Build: Run the following command to compile the TypeScript files into JavaScript.
npm run build
Testing: You can add your tests in the
src
folder and run them using a testing framework like Jest or Mocha.
License
MIT License. See LICENSE for more information.
Author
Le Minh Hieu
5 months ago