var Pile = function() {
this.pile = [];
this.concurrency = 0;
this.done = null;
this.max_concurrency = 10;
}
Pile.prototype = {
add: function(callback) {
this.pile.push(callback);
},
run: function(done, max_concurrency) {
this.done = done || this.done;
this.max_concurrency = max_concurrency || this.max_concurrency;
var target = this.pile.length;
var that = this;
var next = function() {
that.concurrency--;
(--target == 0 ? that.done() : that.run());
};
while(this.concurrency < this.max_concurrency && this.pile.length > 0) {
this.concurrency++;
var callback = this.pile.shift();
callback(next);
}
}
};
pilex = new Pile();
var counter = 0;
for(var i = 0; i < 50; i++) {
pilex.add( function test(next) { //実行する非同期処理を登録
setTimeout( function() {
counter++;
echo(counter +" Hello world");
next();
}, 1500);
}
);
}
pilex.run(function() { //登録した処理を実行
echo("Done "+counter);
},5); //一度に実行する非同期処理の制限数
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
List of users who liked
78