In the following code, I'm attempting to understand the concept of writing asynchronous JavaScript functions. To be clear on my assumptions:
The function logTest() is called. It calls asyncTest(), passing in the log() function. However, asyncTest() doesn't call log() directly. Rather, it passes it to the event queue to be called when the stack clears. The stack shouldn't clear until after the for loop completes, writing twenty "waiting..."'s. However, the console output puts the "async" line first before the for loop. I ran this code in Node.js, in which console.log is a synchronous function. Does anyone know why the "async" line wasn't written last?
function asyncCall(method) {
return setTimeout(method, 0);
}
function log(str) { console.log(str); }
function logTest() {
asyncCall(log("async"));
for(var i = 0; i < 20; i++) {
log("waiting...");
}
}
logTest();