Skip to content

Instantly share code, notes, and snippets.

@fukajun
Created August 24, 2017 05:54
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 fukajun/007f4f1244cd7d89c8a827fa8e1b2dd2 to your computer and use it in GitHub Desktop.
Save fukajun/007f4f1244cd7d89c8a827fa8e1b2dd2 to your computer and use it in GitHub Desktop.
Limit concurency count on javascript
var list = []
for(i = 0; i < 200; i++) {
list.push(i)
}
var semaphore = [true, true, true, true, true, true]
var uploadImage = function(num, callback) {
setTimeout(function() {
console.log('upload', num)
callback()
}, 2000)
}
var startWorker = function() {
var timerId = setInterval(function() {
if(list.length <= 0) {
console.log('end')
clearInterval(timerId)
return;
}
if(semaphore.length >= 1) {
semaphore.shift()
var num = list.shift()
uploadImage(num, function() {
semaphore.push(true)
})
} else {
console.log('waiting....')
}
}, 1000)
}
for(i in semaphore) {
startWorker();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment