Consider the following piece of code:
var some_expensive_task = function(i) {
setTimeout(function() {
var a = 1;
while (a < 100000000) {
Math.sqrt(a);
++a;
}
console.log('finished set' + i);
}, 0);
};
for (var i = 0; i < 70; ++i) {
console.log('start ' + i);
some_expensive_task(i);
console.log('end ' + i);
}
The intent of this program was to iterate over and start 70 cpu intensive asynchronous tasks using setTimeout.
As expected, the output of this program is:
start 1
end 1
...
start 69
end 69
finished set1
...
finished set69
Throughtout the entire execution, there were only two processes. One of which I assume was the idle event loop and the other was the worker process running at 100%.
Am I correct in understanding that while the event loop is executed synchronously, asynchronous tasks that are started, regardless of origin, are executed synchronously in the order that they were called?
UPDATE
I still don't feel as if I've conveyed my question clear enough. Using setTimeout was the only way I could think of to accurately schedule a bunch of async functions to run. I guess the real question is, if I start three async functions with setTimeout, still with a zero delay, is the second one I start guaranteed to run after the first one finishes and is the third one guaranteed to start after the second one finishes?