Skip to content

Instantly share code, notes, and snippets.

@DuaneNielsen
Created January 21, 2016 06:16
Show Gist options
  • Select an option

  • Save DuaneNielsen/99bd2540da070fbda061 to your computer and use it in GitHub Desktop.

Select an option

Save DuaneNielsen/99bd2540da070fbda061 to your computer and use it in GitHub Desktop.
Javascript Barrier Sync with a limited number of threads
function async(arg, callback) {
console.log('do something with \''+arg+'\', return 1 sec later');
setTimeout(function() { callback(arg * 2); }, 1000);
}
function final() { console.log('Done', results); }
var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
var running = 0;
var limit = 2;
function launcher() {
while(running < limit && items.length > 0) {
var item = items.shift();
async(item, function(result) {
results.push(result);
running--;
if(items.length > 0) {
launcher();
} else if(running == 0) {
final();
}
});
running++;
}
}
launcher();
@DuaneNielsen

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment