Update: I now know that throttle will drop excess function invocations, so it is not the correct tool. I'd still like an idiomatic way to process all items in a queue without going too quickly or dropping any items.
I'm writing a node app that hits an API with a rate limit. I can create calls much faster than I'm allowed to send them. I'd like to consume a queue of calls, but without going too quickly or dropping any of them. I made a small typscript test to illustrate my trouble:
import * as _ from "lodash";
let start = new Date().getTime();
function doLog(s: string) {
let elapsed = new Date().getTime() - start;
console.log(`${s} ${elapsed}`);
}
let array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
let throttled = _.throttle(doLog, 100);
array.forEach(s => throttled(s));
I expected to see output roughly like:
a 2
b 101
c 203
d 302
e 405
f 502
g 603
h 706
i 804
j 902
But instead I see:
a 2
j 101
Some odd observations I've made:
- At 100ms throttle, the size of the array seems irrelevant: I will print the first and last item in the array, whether it has 2 elements or 20.
- At 1ms throttle, I print 3-6 elements from the front of the array, and the last element