0

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.

2
  • Why are you using setTimeout with a 0? SetTimeout isn't popped off the stack, it sets up the callback and then executes immediately. Commented Dec 1, 2017 at 22:26
  • I set it to 0 just to observe how it would work in the stack and the queue. Because while the anonymous() is on the queue console.log(square(2)) happens and when the stack is completely empty that's when the event loop is activated and the anonymous() is sent to the stack from the queue. Commented Dec 1, 2017 at 22:32

1 Answer 1

2

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;

Sign up to request clarification or add additional context in comments.

1 Comment

However if you use the tool in the link you will notice that 2nd one happens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.