-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Throttle / rateLimit #240
Comments
For reference Highland (yeah, I'm basically copy pasting their stuff over at this rate 😅) has a
Also, there's I think the implementation would be something like this: async function* _throttle<T>(
num: number,
ms: number,
iterable: AnyIterable<T>
) {
let sent = 0;
let time: number | undefined;
for await (const val of iterable) {
if (sent < num) {
if (typeof time === "undefined") {
time = Date.now();
}
sent++;
yield val;
continue;
}
// Only wait if the window hasn't passed while yielding
// the previous values.
// NOTE: Highland doesn't make this optimisation, but I think it prob should have as if this
// just waited for `ms` it'll likely over throttle if the `yield val` was slow.
const elapsedMs = Date.now() - time!;
const waitFor = ms - elapsedMs;
time = undefined;
waitFor > 0 && (await sleep(waitFor));
if (typeof time === "undefined") {
time = Date.now();
}
sent = 1;
yield val;
}
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); |
Thanks for getting it over the finish line =) |
Hi @reconbot
I wondered if you had considered adding a
throttle
utility which would yield values at a given rate. e.g.My current use case is to process a stream of data which comes in faster than the third party API I'm sending it to can handle, so something like this would be useful, unless you can think of a better solution?
The text was updated successfully, but these errors were encountered: