jQuery.Deferred test

HTML

<input type="button" value="wrong way" class="wrong" /> | <input type="button" value="right way" class="right" />
<section id="mybox"></section>

CSS

#mybox {
  background-color: #eee;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 4px;
  margin: 4px;
}

JavaScript

var $box = jQuery('#mybox');

function second(){
  return jQuery.Deferred(function(dfd){
    setTimeout(function(){
      $box.append('<div>second (or third)</div>');
      dfd.resolve();
    }, Math.ceil(Math.random() * 10) * 100);
  }).promise();
}

function third(){
  return jQuery.Deferred(function(dfd){
    setTimeout(function(){
      $box.append('<div>third (or second)</div>');
      dfd.resolve();
    }, Math.ceil(Math.random() * 10) * 100);
  }).promise();
}

function fourth(){
  setTimeout(function(){
    $box.append('<div>fourth (should always be last)</div>');
  }, 500);
}

function wrong(){
  $box.empty();
  jQuery.when((function(){
    return jQuery.Deferred(function(dfd){
      setTimeout(function(){
        $box.append('<div>first (deferred)</div>');
        dfd.resolve();
      }, 250);
    }).promise();
  }()))
    .done(second, third)
    .done(fourth);
}

function right(){
  $box.empty();
  jQuery.when((function(){
    return jQuery.Deferred(function(dfd){
      setTimeout(function(){
        $box.append('<div>first (deferred)</div>');
        dfd.resolve();
      }, 250);
    }).promise();
  }()))
    .pipe(function(){
      return jQuery.when(second(), third());
    })
    .done(fourth);
}

jQuery('input').on('click', function(){
  if (jQuery(this).hasClass('wrong')) {
    wrong();
  } else if (jQuery(this).hasClass('right')) {
    right();
  }
});