LoginSignup
7
8

More than 5 years have passed since last update.

一度に実行する非同期処理の数を制限して、何回かに分けて処理する

Posted at
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);  //一度に実行する非同期処理の制限数

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8