@se-oss/throttle is a utility for rate-limiting function calls. It is designed for modern applications that require fine-grained control over asynchronous operations, offering 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 now = Date.now();
const throttled = throttle(
async (index: number) => {
const secDiff = ((Date.now() - now) / 1000).toFixed();
return `${index}: ${secDiff}s`;
},
{
limit: 2,
interval: 1000,
}
);
for (let index = 1; index <= 6; index++) {
(async () => {
console.log(await throttled(index));
})();
}
//=> 1: 0s
//=> 2: 0s
//=> 3: 1s
//=> 4: 1s
//=> 5: 2s
//=> 6: 2sAbort pending executions using an AbortSignal.
import { throttle } from '@se-oss/throttle';
const controller = new AbortController();
const throttled = throttle(
() => {
console.log('Executing...');
},
{
limit: 2,
interval: 1000,
signal: controller.signal,
}
);
await throttled();
await throttled();
controller.abort('aborted');
await throttled();
//=> Executing...
//=> Executing...
//=> Promise rejected with reason `aborted`Get notified when function calls are delayed.
import { throttle } from '@se-oss/throttle';
const throttled = throttle(
(a, b) => {
console.log(`Executing with ${a} ${b}...`);
},
{
limit: 2,
interval: 1000,
onDelay: (a, b) => {
console.log(`Call is delayed for ${a} ${b}`);
},
}
);
await throttled(1, 2);
await throttled(3, 4);
await throttled(5, 6);
//=> Executing with 1 2...
//=> Executing with 3 4...
//=> Call is delayed for 5 6
//=> Executing with 5 6...Use the weight option to assign a custom cost to each function call.
import { throttle } from '@se-oss/throttle';
// API allows 100 points per second.
// Each call costs 1 point + 1 point per item.
const throttled = throttle(
async (itemCount: number) => {
// Fetch data
},
{
limit: 100,
interval: 1000,
weight: (itemCount: number) => 1 + itemCount,
}
);
await throttled(10); // Costs 11 points
await throttled(50); // Costs 51 pointsCheck the number of queued items.
import { throttle } from '@se-oss/throttle';
const accurateData = throttle(() => fetch('...'), {
limit: 1,
interval: 1000,
});
const fallbackData = () => fetch('...');
async function getData() {
if (accurateData.queueSize >= 5) {
return fallbackData(); // Use fallback when queue is full
}
return accurateData();
}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.