@se-oss/throttle
v1.0.2
Published
A utility for rate-limiting function calls.
Maintainers
Readme
@se-oss/throttle is a utility for rate-limiting function calls, offering fine-grained control with features like strict mode, weighted throttling, and abort signals.
📦 Installation
npm install @se-oss/throttlepnpm
pnpm install @se-oss/throttleyarn
yarn add @se-oss/throttle📖 Usage
Basic Usage
Throttle a function to be called at most twice per second.
import { throttle } from '@se-oss/throttle';
const throttled = throttle(async (id) => fetchData(id), {
limit: 2,
interval: 1000,
});
for (let i = 1; i <= 6; i++) {
throttled(i).then(console.log);
}Abort Signal
Abort pending executions using an AbortSignal.
import { throttle } from '@se-oss/throttle';
const controller = new AbortController();
const throttled = throttle(work, {
limit: 1,
interval: 1000,
signal: controller.signal,
});
await throttled();
controller.abort('stopped');
await throttled(); // Rejects with 'stopped'Delay Notifications
Get notified when function calls are delayed due to limits.
const throttled = throttle(work, {
limit: 1,
interval: 1000,
onDelay: (...args) => console.log('Delayed:', ...args),
});Weighted Throttling
Assign custom costs to different function calls.
const throttled = throttle(fetchItems, {
limit: 100,
interval: 1000,
weight: (count) => 1 + count,
});
await throttled(10); // Costs 11 pointsQueue Management
Monitor and manage the execution queue size.
const throttled = throttle(work, { limit: 1, interval: 1000 });
if (throttled.queueSize < 5) {
await throttled();
}📚 Documentation
For all configuration options, please see the API docs.
🤝 Contributing
Want to contribute? Awesome! To show your support is to star the project, or to raise issues on GitHub.
Thanks again for your support, it is much appreciated! 🙏
License
MIT © Shahrad Elahi and contributors.
