Skip to content

Instantly share code, notes, and snippets.

@da1z
Created May 30, 2020 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save da1z/beeb6f18b7178d890a816da8da004f65 to your computer and use it in GitHub Desktop.
Save da1z/beeb6f18b7178d890a816da8da004f65 to your computer and use it in GitHub Desktop.
RequestQueue
class RequestQueue {
constructor() {
this.interval = 1000;
this.size = 10;
this.queue = [];
this.intervalToken = null;
this.runningCount = 0;
}
enqueue(url) {
this.queue.unshift(url);
this._dequeue();
}
_dequeue() {
if (this.intervalToken) return;
this.intervalToken = setInterval(() => {
if (!this.queue.length) {
clearInterval(this.intervalToken);
return;
}
while (this.runningCount < this.size && this.queue.length) {
const url = this.queue.pop();
this.runningCount++;
this._makeRequest(url)
.then(() => {
this.runningCount--;
})
.catch(() => {
this.runningCount--;
});
}
}, this.interval);
}
_makeRequest(url) {
return this._sleep(Math.random() * 1000);
}
_sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment