JQuery Progressbar with Deferred Object

Shows a progress bar which is controlled by a jQuery.Deferred object

by Avinash_R

HTML

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<div id="switcher"></div>
<div class="floater">
<div id="progressbar"><span class="centerFloat">Loading...</span></div>
</div>
<script type="text/javascript"
  src="http://jqueryui.com/themeroller/themeswitchertool/">
</script>

CSS

.floater{
    position:fixed;
    width:100%;
    bottom:0px;
}
#progressbar{
    position: relative;
    height 20px;
}
.centerFloat{
    position: absolute;
    left:40%;
    top:10%;
}

JavaScript

function asyncEvent() {
    var dfd = new jQuery.Deferred();
    var timeDone = Math.floor(12000 + Math.random() * 2000);
    var timeError = Math.floor(12000 + Math.random() * 2000);

    // Resolve after a random interval
    setTimeout(function() {
        dfd.notify(100);
        dfd.resolve("hurray");
    }, timeDone);

    // Reject after a random interval
    setTimeout(function() {
        dfd.notify(0);
        dfd.reject("sorry");
    }, timeError);

    // Show a "working..." message every half-second
    var s = 0,
        delay = 500;
    setTimeout(function working() {
        var waitTime = Math.min(timeDone, timeError);
        if (dfd.state() === "pending") {
            dfd.notify((s / waitTime) * 100);
            setTimeout(working, delay);
            s += delay;
        }
    }, 1);

    // Return the Promise so caller can't change the Deferred
    return dfd.promise();
}

// Attach a done, fail, and progress handler for the asyncEvent
$(document).ready(function() {
    $('#switcher').themeswitcher({
        loadTheme: 'Black Tie'
    });
    var pb = $("#progressbar").progressbar({});
    $.when(asyncEvent()).then(

    function(status) {
        pb.find('.centerFloat').text('');
        pb.parent().prepend('<div>' + status + ', things are going well' + '<div>');
    }, function(status) {
        pb.find('.centerFloat').text('');
        pb.parent().prepend('<div>' + status + ', you fail this time' + '<div>');
    }, function(val) {
        pb.progressbar('option', 'value', val);
    });
});