@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.
npm install @se-oss/throttleInstall using your favorite package manager
pnpm
pnpm install @se-oss/throttleyarn
yarn add @se-oss/throttleThrottle 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 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'Get notified when function calls are delayed due to limits.
const throttled = throttle(work, {
limit: 1,
interval: 1000,
onDelay: (...args) => console.log('Delayed:', ...args),
});Assign custom costs to different function calls.
const throttled = throttle(fetchItems, {
limit: 100,
interval: 1000,
weight: (count) => 1 + count,
});
await throttled(10); // Costs 11 pointsMonitor and manage the execution queue size.
const throttled = throttle(work, { limit: 1, interval: 1000 });
if (throttled.queueSize < 5) {
await throttled();
}For all configuration options, please see the API docs.
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! π
MIT Β© Shahrad Elahi and contributors.