a/20329444/1636522

by wared

CSS

*{font-family:Consolas}
.line{padding:2px 0;border-bottom:1px solid #ccc}

JavaScript

// Stack

var Stack = function (maxCalls, stack) {
    this.ongoing = 0;
    this.maxCalls = maxCalls;
    Array.prototype.push.apply(this, stack);
    this.next(); // starts immediately
};

Stack.prototype = Object.create(Array.prototype);

Stack.prototype.next = function () {
    var me = this;
    while (this.length && this.ongoing < this.maxCalls) {
        this.ongoing++;
        // calls the next function
        // passing a callback as a parameter
        this.shift()(function () {
            me.ongoing--;
            me.next();
        });
    }
};

// playground

var stack = new Stack(3, [
    test('hello 1'),
    test('hello 2'),
    test('hello 3'),
    test('hello 4'),
    test('hello 5'),
    test('hello 6')
]);

function test(elem) {
    return function (callback) {
        output(elem + ' fired');
        // asynchronous operation :
        defer(function () {
            output(elem + ' completed');
            callback();
        });
    };
}

// helpers

function output(s) {
    document.body.innerHTML += '<div class="line">' + s + '</div>';
}

function defer(callback) {
    var duration = Math.floor(Math.random() * 4) + 1;
    setTimeout(callback, duration * 1000);
}