简体   繁体   中英

JavaScript Stack, Queue and the Event Loop?

I'm trying to verify the order in which the following code happens.

function square(n) {
    return n * n;
}

setTimeout(function(){
    console.log("Hello");
}, 0);

console.log(square(2));
  1. setTimeout() is popped off the stack, and then anonymous() goes to the queue.

  2. While setTimeout() is on the stack, anonymous() goes to the queue, and then setTimeout() is popped off the stack.

Which of the above is the correct order? I tried it on this link and what I've noticed is that setTimeout() is popped of first and then anonymous() goes to the queue but I just need to verify this.

The first is answer is correct. The setTimeout function gets popped off then anonymous(), the inner unnamed function written as the first argument in the setTimeout, is sent to the queue and will remain there, until all other code runs;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM