0

Please have a look at code below:

setTimeout(() => {console.log('A')}, 3000);
setTimeout(() => {console.log('B')}, 1000);
setTimeout(() => {console.log('C')}, 500);

since setTimeout adds message to message queue and messages are FIFO queue, and one message needs to finish before next one may start, I expect to see A B C order but I see C B A.

It means that I do not understand something here. What is it that I do not understand?

1
  • 2
    The callback is added to the queue after the given timeout, so setTimeout with 500ms timeout will be added to the queue first, and so on. Commented May 4, 2022 at 10:21

2 Answers 2

1

The setTimeout is provided to us by the Web API: it lets us delay tasks without blocking the main thread. The callback doesn’t immediately get added to the call stack. It simply gets added to the queue after setTimeout time.

In this article you can have more details and visualization about event loop.

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

Comments

1

According to this article

The function setTimeout is called with 2 arguments: a message to add to the queue, and a time value (optional; defaults to 0). The time value represents the (minimum) delay after which the message will be pushed into the queue. If there is no other message in the queue, and the stack is empty, the message is processed right after the delay.

That means the message queue also knows how to handle the delays.

Comments

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.