JSFiddle - React, Tailwind, and code Playground

by asdf

JavaScript

function Runner (n) {
  this.limit = n;
  this.counter = 0;
  this.queue = [];
}

Runner.prototype.push = function (task) {
	var self = this;
  if (this.counter === this.limit) {
    this.queue.push(task);
  } else {
    this.counter += 1;
    task(callback);
  }
  function callback () {
    self.counter -= 1;
    if (self.queue.length) {
      self.counter += 1;
      self.queue.shift()(callback);
    }
  }
}

function exampleTask (i) {
  return function (done) {
    console.log(i);
    setTimeout(done, 1000);
  };
}

var run = new Runner(3);
run.push(exampleTask(1));
run.push(exampleTask(2));
run.push(exampleTask(3));
run.push(exampleTask(4)); // later
run.push(exampleTask(5)); // later