My question is variant of this question: setTimeout executes after for loop in javascript
The code:
let i = 0;
setTimeout(() => alert(i), 100); // ?
// assume that the time to execute this function is >100ms
for(let j = 0; j < 100000000; j++) {
i++;
}
The output:
100000000
My Question:
I know that when we're using setTimeout with delay of 100 the WEB API setTimeout() will move to the queue of the eventloop and after that will get inside the call stack if it's empty and available.
We can see that this setTimeout will start after 100ms so i thought maybe the i value would be somthing like 4000+ or somthing like that.
but unfortunately (with this big loop that take like 5+- seconds that is 5000ms) the setTimeout function will be executed just after the for loop finishes! but the event loop daemon is running and ready to accept the setTimeout callback because the call stack is empty.
I know that JS concurrency concept is diffrent from languages just like JAVA&C++, etc... that there is no scheduler for the CPU time because it's one threaded language, but I guess that the event loop working like OS daemon and ready to accept the message from the queue even if the CPU is busy with the for loop.
so the reason that it's happening is because the CPU is busy and can't execute the eventloop ? or there is other reason?
Thanks guys!