Search code examples
jquerysettimeoutshow-hide

Using when and done and settimeout show hide div


function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  $.when(
    setTimeout(function() {
      closecustomBox();
    }, 3000)
  ).done(function(x) {
    $('#anotherdialog').show();
  });
})
#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dialog"></div>

<div id="anotherdialog"></div>


<div id="show">show</div>

What I want to happened is after clicking show will show the red box after 3 seconds the red box will hide then the blue box should show.

I want to achieve here is to not make the 2 div appear together


Solution

  • If you wanted to use $.when then you need to pass in a $.Deferred() as an argument. Then resolve the $.Deferred() once the timeout completes which will call the method that we passed to .done() previously.

    I also set the initial state of the dialogs via CSS to display: none; to avoid the need for hiding them via JS initially.

    I've also provided an alternative which doesn't use jQuery deferred's which achieves the same results.

    function closecustomBox() {
      $('#dialog').hide();
    }
    
    var dialog = $('#dialog');
    var anotherDialog = $('#anotherdialog');
    var timeout;
    
    $("#show").click(function() {
      dialog.show();
      anotherDialog.hide();
    
      def = $.Deferred();
      $.when(def).done(function() {
        closecustomBox();
        anotherDialog.show();
      });
    
      if (timeout) clearTimeout(timeout); // Clear out any old timeouts to avoid flickers and strange behavior
      timeout = setTimeout(function() {
        def.resolve(); // Resolve the Deferred which will call def.done's callback
      }, 3000);
    })
    
    // Or if you don't want to use promises you can just elminate them entirely and simplify this example greatly
    var timeout2;
     $("#show-2").click(function() {
          dialog.show();
          anotherDialog.hide();
    
          if (timeout) clearTimeout(timeout); // Clear out any old timeouts to avoid flickers and strange behavior
          timeout = setTimeout(function() {
            closecustomBox();
            anotherDialog.show();
          }, 3000);
        })
    #anotherdialog {
      width: 100px;
      height: 100px;
      background-color: blue;
      display: none;
    }
    
    #dialog {
      width: 101px;
      height: 101px;
      background-color: red;
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="dialog"></div>
    
    <div id="anotherdialog"></div>
    
    
    <div id="show">show</div>
    
    <div id="show-2">Alternate Show</div>