@se-oss/throttle
v1.0.0
Published
A utility for rate-limiting function calls.
Downloads
45
Maintainers
Readme
@se-oss/throttle
@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.
📦 Installation
npm install @se-oss/throttlepnpm
pnpm install @se-oss/throttleyarn
yarn add @se-oss/throttle📖 Usage
Basic Throttling
Throttle 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 Signal
Abort 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`onDelay
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...weight
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 pointsqueueSize
Check 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();
}📚 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.
