Javascript with Chorme V8 engine works like this:
For Chorme engine, V8, it has a call stack.
And all the async opreations functions is stay in Webapis. So everytime to SetTimeout () ' or HTTP call, it'll always call Webapis.
So, with the picture,
We call the main () function, and push into the call stack;
Then Console.log ("Hi"); Put into call stack and finish then poped up from the call stack;
Third, setTimeout () function run into the call stack, then it call Webapis with callback function, so push into Webapis. and SetTimeout () popup from the call stack.
Fourth, Console.log (' JSC '); Push into the call stack and poped up.
Finally Main () finished and poped up:
So why left here is just Webapis has a callback function, waiting 5 second, when the time out, it was push to the TA SK queue, not to the call stack.
Now the "event loop ' come in," what event loop does are: it check whether there is an any task in the call stack .... If yes , finish those functions in the CALLL stack first. If not, then event loop checks the task queue then push the callback from the task queue to call stack.
Then Console.log () function run and poped to the call stack.
-----------------------------------------
You might has met the problem so you run SetTimeout (FN (), 0); It wait no time, but the FN () come at last:
function One () { console.log ("one");} function Both () { Console.log ("a");} function delay () { console.log ("delay"0); /* "One" "" "" Delay " */
That is because, setTimeout are Webapis, so the callback function delay () would be pushed into the ' task queue '. It'll wait all the functions in ' Call stack ' finish, then even loop would check the task queue and push the callback to T He call stack. The "Delay" console log out at the bottom.
Link:https://www.youtube.com/watch?v=8aghzqkofbq
[Javascript] Task Queue & Event loop.