Created
May 30, 2020 22:11
-
-
Save da1z/beeb6f18b7178d890a816da8da004f65 to your computer and use it in GitHub Desktop.
RequestQueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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