rate-limiter-utils is an npm package designed to optimize how frontend applications interact with APIs. It helps manage API request rates by implementing debouncing and throttling techniques, which improve performance and prevent issues like exceeding API rate limits.
-
Debouncing: Delays the execution of a function until a specific time has passed since its last call. Ideal for reducing unnecessary API calls triggered by frequent events, such as user input in a search field.
-
Throttling: Limits how often a function can be called within a set timeframe. Useful for handling high-frequency actions like scrolling or mouse movements.
-
🚀 Boost application performance by reducing unnecessary API requests.
-
⚡ Prevent API rate limits from being reached and improve the overall user experience.
-
💡 Optimize resource usage by managing network traffic and CPU load more efficiently.
You can install rate-limiter-utils
via npm:
npm install rate-limiter-utils
Here's how you can use the debounce and throttle functions in your frontend application:
- Standard debounce (function executes after delay):
import { debounce } from 'rate-limiter-utils';
const debouncedFunction = debounce(() => console.log('Executed!'), 300);
debouncedFunction(); // Will log "Executed!" after 300ms
- Immediate execution (executes immediately and then debounced):
If immediate is true, the function is executed at the start and then debounced. If false, it behaves like a standard debounce function.
import { debounce } from 'rate-limiter-utils';
const debouncedFunction = debounce(() => console.log('Executed!'), 300, true);
debouncedFunction(); // Will log "Executed!" after 300ms
- Standard throttle (function is invoked every delay ms at most):
import { debounce } from 'rate-limiter-utils';
const throttledFunction = throttle(() => console.log('Throttled function!'), 300);
throttledFunction(); // Will log "Throttled function!" if enough time has passed since the last call
- Immediate execution (function is executed immediately, and then throttled):
If immediate is true, the function is executed at the start and then throttled. If false, it behaves like a standard throttling function.
import { debounce } from 'rate-limiter-utils';
const throttledImmediateFunction = throttle(() => console.log('Throttled function!'), 300, true);
throttledImmediateFunction(); // Will log immediately on the first call, and throttle subsequent calls
- TypeScript: Ensures type safety and better developer experience.
- Node.js: Runtime for building the package.
This project is licensed under the MIT License.
Developed by Anurag Kumar.
- Email: anuragkmr45@gmail.com