iter-tools-es
Version:
The iterable toolbox
33 lines (27 loc) • 798 B
JavaScript
const {
asyncIterableCurry
} = require('../../internal/async-iterable.js');
const {
isPositiveInteger
} = require('../../internal/number.js');
const {
delay
} = require('../../internal/delay.js');
async function* __asyncThrottle(source, intervalMs) {
let waitSince = 0;
for await (const value of source) {
const duration = intervalMs - (Date.now() - waitSince);
await (duration > 0 && delay(duration));
waitSince = Date.now();
yield value;
}
}
exports.__asyncThrottle = __asyncThrottle;
const asyncThrottle = /*#__PURE__*/asyncIterableCurry(__asyncThrottle, {
validateArgs(args) {
if (!isPositiveInteger(args[1], true)) {
throw new Error('intervalMs argument to asyncThrottle must be a number > 0');
}
}
});
exports.asyncThrottle = asyncThrottle;