jQuery - Async demo

http://stackoverflow.com/questions/16254098/get-in-a-loop-why-the-function-is-performed-after-incrementing

HTML

<pre id="output"></pre>

JavaScript

$("#output").empty();
    
    var startTime = new Date().getTime();
    
    // try experimenting with async = true/false and the delay
    // don't set async to false with too big a delay,
    // or too high a count,
    // or you could hang your browser for a while!
    // When async==false, you will see each callback respond in order, followed by "Loop finished".
    // When async==true, you could see anything, in any order.
    var async = true;
    var delay = 1;
    var count = 5;
    
    function createClosure(i) {
        // return a function that can 'see' i.
        // and i's remains pinned within this closure
        return function (resp) {
            var duration = new Date().getTime() - startTime;
            $("#output").append("\n" + i + " returned: " + resp + " after " + duration + "ms");
        };
    }
    
    for (var i = 0; i < count; i++) {
        // jsfiddle url and params
        var url = "/echo/html/";
        var data = {
            html: "hello " + i,
            delay: delay
        };
    
        $.ajax(url, {
            type: "post",
            data: data,
            async: false,
            beforeSend: function(){
    					$("#output").append('test')        
            }
        }).then(createClosure(i));
    }
    
    var duration = new Date().getTime() - startTime;
    $("#output").append("\n" + "Loop finished after " + duration + "ms");