Boostrap Modal Sync Work Around

for Bootstrap, modal showing/hiding are time dependent. You can't hide until after the show has completed, which normally takes 450ish ms. This work fiddle queues up actions, calling them once the modal is done performing the current action

by Daryl LaBar

HTML

<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<div id="loadingModal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <p>Loading...</p>
      </div>
    </div>
  </div>
</div>
<button id="btnShow">Show Loading</button>
<button id="btnProblem">Cause show/hide problem</button>
<p id="log">
</p>

JavaScript

var loadingModal = $("#loadingModal");

var actionInProgress = false;
var nextActionQueue = [];

function showModal(modal) {
  if (actionInProgress) {
    nextActionQueue.push({
      id: modal.attr('id'),
      action: showModal
    });
    return;
  }

  actionInProgress = true;
  modal.on('shown.bs.modal', showCompleted);
  modal.modal("show");

  function showCompleted() {
    actionInProgress = false;
    modal.off('shown.bs.modal', showCompleted);
    if (nextActionQueue.length > 0) {
      var next = nextActionQueue.shift();
      next.action($("#" + next.id));
    }
  }
};

function hideModal(modal) {
  if (actionInProgress) {
    nextActionQueue.push({
      id: modal.attr('id'),
      action: hideModal
    });
    return;
  }
  
  actionInProgress = true;
  modal.on('hidden.bs.modal', hideCompleted);
  modal.modal("hide");

  function hideCompleted() {
    actionInProgress = false;
    modal.off('hidden.bs.modal', hideCompleted);
    if (nextActionQueue.length > 0) {
      var next = nextActionQueue.shift();
      next.action($("#" + next.id));
    }
  }
};

$("#btnShow").click(function() {
  showModal(loadingModal);
  hideModal(loadingModal);
  showModal(loadingModal);
  hideModal(loadingModal);
  setTimeout(function() {
    showModal(loadingModal);
    hideModal(loadingModal);
  }, 500);
});

$("#btnProblem").click(function() {
  //simulate a loading screen finishing fast, followed by another loading screen
  loadingModal.modal("show");
  loadingModal.modal("hide");
  loadingModal.modal("show");
});