rjweb-server
Version:
Easy and Robust Way to create a Web Server with Many Easy-to-use Features in NodeJS
27 lines (26 loc) • 761 B
JavaScript
export default class Throttler {
constructor(bytes) {
this.sent = 0;
this.lastSent = Date.now();
this.bytes = bytes;
}
/**
* Insert Data into the Throttler and wait for it to be sent
* @since 9.0.0
*/ async insert(data) {
const now = Date.now();
if (now - this.lastSent >= 1000) {
this.sent = data.byteLength;
this.lastSent = now;
}
else {
if (this.sent + data.byteLength > this.bytes) {
await new Promise((resolve) => setTimeout(resolve, 1000 - (now - this.lastSent)));
this.sent = data.byteLength;
}
else {
this.sent += data.byteLength;
}
}
}
}