[Javascript] Task Queue & Event loop.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.