Skip to content

Instantly share code, notes, and snippets.

@sjy
Created January 23, 2019 12:25
Show Gist options
  • Save sjy/8f59e4190aa1dc0c4a92a7920f2c0c02 to your computer and use it in GitHub Desktop.
Save sjy/8f59e4190aa1dc0c4a92a7920f2c0c02 to your computer and use it in GitHub Desktop.
quene with max parallel task limits
export default class RequestQuene {
constructor(limits = 10, duration = 200) {
this.duration = duration
this.limits = limits
this.q = []
this.intervalId = null
this.intervalDuration = duration
this.numOfRunning = 0
}
check = () => {
if (this.numOfRunning < this.limits) {
this.q.splice(0, this.limits - this.numOfRunning).forEach(run => run())
if (this.q.length === 0 && this.intervalId) {
clearInterval(this.intervalId)
this.intervalId = null
}
}
}
enquene(run) {
this.q.push(run)
if (!this.intervalId) {
this.intervalId = setInterval(this.check, this.intervalDuration)
}
}
add(request) {
return new Promise((resolve, reject) => {
const run = () => {
this.numOfRunning++
try {
request()
.then(res => {
resolve(res)
}, err => {
reject(err)
})
.finally(() => {
this.numOfRunning--
})
} catch (e) {
this.numOfRunning--
reject(e)
}
}
if (this.numOfRunning < this.limits) {
run()
} else {
this.enquene(run)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment