With a need to call multiple processes in series using synchronous AJAX calls, I aim to display the status of each long-running process upon completion before proceeding to the next. Below is an excerpt from the code that illustrates this concept:
var counter = 0;
function runProcess(input, output) {
doWork();
doWork();
doWork();
};
function doWork() {
counter++;
document.getElementById('<%=this.progressMonitor.ClientID%>').innerHTML += "Running " + counter;
// performing 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;
}
Upon running this code snippet, the output received consist of repeated 'Running' and 'Done' logs as follows:
Running 1Running 2Running 3Done 3Done 3Done 3
The desired outcome is closer to:
Running 1Done 1Running 2Done 2Running 3Done 3
Including an alert() statement within the updateStatus function seems to achieve the desired execution order. Could it be that the browser initiates separate threads for each function call and executes them asynchronously?
To ensure the processes run sequentially, could there be an issue with how setTimeout is implemented? Your insights on this matter would be greatly appreciated.