The order of output on the browser console is not what I expected in the code given below.
I have two functions, each with a simple counter. Each time the counter reaches a multiple of some value two things are output. First the current value of the counter is output to the console and a letter (either “a” or “c”, depending on the function being processed) is scheduled for output via a callback in a setTimeout function that has a specified delay of 0.
In the main code, function a() is first called, then an arbitrary variable is assigned, then function c() is called. When I run the code, the return values for each function are printed first (and in the expected order) then the counter values are printed for BOTH functions. Only after this are the letters “a” and “c” printed (five times each).
My understanding is that the setTimeout() function schedules a call to the callback functions when the call stack is empty.
Is the call stack empty between function calls to a() and c()? If so, why does the setTimeout() function of function a() schedule its output after BOTH functions a() and c() have completed? Or, if not, how do I make sure the call stack is (periodically) empty in order to get output from callback functions?
function a() {
for (let b = 0; b < 5000000000; b++) {
if (b % 1000000000 == 0) {
console.log(b);
setTimeout(function() {
console.log("a")
}, 0);
}
}
return 2;
}
function c() {
for (let b = 0; b < 5000000000; b++) {
if (b % 1000000000 == 0) {
console.log(b);
setTimeout(function() {
console.log("c")
}, 0);
}
}
return 4;
}
console.log( a() );
let z = 0;
console.log ( c() );
Expected output
I expected that, at least, “a” would be printed before function c() was called.
Sean Karl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.