var tds = ["0", "1", "2", "3", "4", "5", "6"];
for (var i = 0; i < tds.length; i++) {
jQuery("#notification-bar").html('I am doing ' + tds[i]);
jQuery.ajax({
url: "/ajax_json_echo/",
type: "POST",
timeout: 10000,
data: tds[i],
success: function(response) {
},
error: function(x, t, m) {
}
});
} //end for
jQuery("#notification-bar").html("Done!");
/ajax_json_echo/ might take 10 seconds or even more to deal with tds.
The expected result of notification bar is
I am doing 0
I am doing 1
I am doing 2
…
Done!
The actual result I get is:
Done!
I guess it is caused by the async variable of jquery ajax is being set to true.
If it is set to false, the browser will be frozen. When it recovers, I get "Done!" only.
The browser runs JavaScript and does page rendering all on the same thread, so while JS is running no repaints will occur. This means that your entire for loop will complete and the status message will be set to “Done!” before the page gets updated.
In the case of async being true all of the Ajax requests are queued up initially and the message set to “Done!” and then the responses are processed later asynchronously. In the case of async set to false the Ajax requests are done one at a time with no further action until the response comes in. Either way the browser never gets a chance to display the “I am doing…” messages.
Rather than using a loop you can trigger each subsequent call from within the Ajax complete (or success) callback:
Each time
doNextAjax()is called it updates the status message and makes a single Ajax request and that’s all. When the function exits the browser then has a chance to re-render and actually show that message. Then when the complete callback is fired it calls the function again for the next item. When there are no items left it sets the “Done!” message.Note that using the complete callback to trigger the next Ajax call means that it will keep going even if a particular request fails. If you wanted to stop on error you could get rid of the complete handler and move the
doNextAjax(i+1)into the success callback.