Edit in JSFiddle

function Mutex() {
    this.isLocked = false;
    this._waiting = [];
    this._index = 0;
}

Mutex.prototype.lock = function (cb) {
    if (this.isLocked) {

        // Original line, this._waiting.push(cb);
        this._waiting.splice(this._index, 0, cb);

    } else {
        this.isLocked = true;
        cb();
    }
}

Mutex.prototype.unlock = function () {
    if (!this.isLocked) {
        throw new Error('Mutex is not locked');
    }

    var waiter = this._waiting[this._index];

    if (waiter) {
        this._index++;
        waiter();
    } else {
        this.isLocked = false;
    }
}

var mutex = new Mutex();

function log(text) {
  var el = document.getElementById("results");
  el.innerHTML += text + "<br>";
}

mutex.lock(function () {

  mutex.lock(function () {
    
    mutex.lock(function () {
      log("car");
    
      mutex.lock(function () {
        log("quz");  
        mutex.unlock();
      });
    
      mutex.unlock();
    });
    
    log("bar");
   
    mutex.lock(function () {
      log("baz");
      mutex.unlock();
    });
    
    // this will unlock the last acquired lock
    // so the above code is executed
    
    mutex.unlock();
  });
  
  log("foo");
  mutex.unlock();

});
// Original : <a href="https://github.com/Wizcorp/locks/">Wizcorp/locks/</a><br>
// License : MIT <br>http://jsfiddle.net/#run

<div id="results"></div>