Skip to content

Instantly share code, notes, and snippets.

@11bit
Created November 16, 2016 10:55
Show Gist options
  • Save 11bit/d03fa4b6ea2ed88ad9194613c92f6726 to your computer and use it in GitHub Desktop.
Save 11bit/d03fa4b6ea2ed88ad9194613c92f6726 to your computer and use it in GitHub Desktop.
function ThrottledQueue(){
let queue = []
let runningJobs = 0
function nextJob() {
runningJobs++
setImmediate(() => {
if (queue.length > 0)
queue.pop().runJob()
})
})
function wrapJob(job) {
let runJob
let jobPromise = new Promise(resolve => {
runJob = resolve
}).then(job)
let wrappedJob = {
runJob: runJob,
jobPromise: jobPromise,
}
jobPromise.finally(() => {
runningJobs--
nextJob(wrappedJob)
})
return jobPromise
}
return {
push(job) {
let wrapped = wrapJob(job)
queue.push(wrapped)
if (runningJobs <= 5) {
nextJob()
}
return wrapped.jobPromise
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment