I have mutiple processes that need to be called in series (I am using synchronous AJAX calls). I would like to display status of a long running process after its completion and then proceed to the next one. Here is a sample code I have written.
var counter = 0;
function runProcess(input, output) {
doWork();
doWork();
doWork();
};
function doWork() {
counter++;
document.getElementById('<%=this.progressMonitor.ClientID%>').innerHTML += "Running " + counter;
// some lengthy calculations
for (var i = 0; i < 1000000; i++) {
var foo = Math.random();
}
setTimeout(updateStatus, 1000);
};
function updateStatus() {
document.getElementById('<%=this.progressMonitor.ClientID%>').innerHTML += "Done " + counter;
}
When I run this, I get the following response:
Running 1Running 2Running 3Done 3Done 3Done 3
I would like to get
Running 1Done 1Running 2Done 2Running 3Done 3
If I insert a alert() statement in updateStatus function, then I get the response/execution order I want. Is the browser creating 3 threads for 3 function calls and executing them asynchronously?
How can I run this in series? Is setTimeout implemented correctly? Thanks for your help in advance.
It sounds like you want to queue up AJAX calls. jQuery provides a good queue function, so you can make sure a series of functions gets called one after the other. Mootools and other frameworks provide similar functionality.
Here is the code from my fiddle that shows how to do it.