Running async functions sequentially

http://stackoverflow.com/questions/14412026/jquery-how-to-run-a-function-as-soon-as-another-function-ends

by zarjay

HTML

<div class="container">
    <div class="one box">1</div>
    <div class="two box">2</div>
    <div class="three box">3</div>
    <div class="four box">4</div>
    <div class="five box">5</div>
</div>

CSS

.container {overflow:auto;}
.box { width:100px; height:100px; line-height:100px; font-size:2em; text-align:center; float:left; }
.one {background:red;}
.two {background:green;}
.three {background:blue;}
.four {background:orange;}
.five {background:yellow;}

JavaScript

function one(){
    var deferred = $.Deferred();
    $(".one").fadeOut(500, function() {
        $(this).appendTo('body').fadeIn(500, function() { deferred.resolve(); });
    });
    return deferred.promise();
}

function two(){
    var deferred = $.Deferred();
    $(".two").fadeOut(1500, function() {
        $(this).appendTo('body').fadeIn(500, function() { deferred.resolve(); });
    });
    return deferred.promise();
}

function three(){
    var deferred = $.Deferred();
    $(".three").fadeOut(1000, function() {
        $(this).appendTo('body').fadeIn(500, function() { deferred.resolve(); });
    });
    return deferred.promise();
}

function four(){
    var deferred = $.Deferred();
    $(".four").fadeOut(750, function() {
        $(this).appendTo('body').fadeIn(500, function() { deferred.resolve(); });
    });
    return deferred.promise();
}

function five(){
    var deferred = $.Deferred();
    $(".five").fadeOut(600, function() {
        $(this).appendTo('body').fadeIn(500, function() { deferred.resolve(); });
    });
    return deferred.promise();
}

one()
	.then(two)
	.then(three)
	.then(four)
	.then(five);