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?
CodePudding user response:
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.
CodePudding user response:
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
.