3

First of all, the docs have clearly stated that in a I/O cycle, setImmediate() will always run before setTimeout(). What is bugging me is that they didn't explain why it functions like that, and looking for clues in the previous statements in their docs somehow pointed out to me the opposite (that setTimeout() should be called first). Here's why:

When the callback finishes, there are no more callbacks in the queue, so the event loop will see that the threshold of the soonest timer has been reached then wrap back to the timers phase to execute the timer's callback

and

Once the poll queue is empty the event loop will check for timers whose time thresholds have been reached. If one or more timers are ready, the event loop will wrap back to the timers phase to execute those timers' callbacks.

So it seems like the first thing the event loop prioritizes to do after exhaust the poll queue is to check the timers and wraps back there if they are timeouted. So in that regard it should be the setTimeout() be executed first.

I'm no advance programmer who can read source code in github to see how the libuv library works internally. Really appreciate some help from you guys.

Best_Name
  • 149
  • 2
  • 13
  • Note: I know this is old, but leaving this for reference to newcomers, ------------------------------------ this is related to how microtask and tasks run, check this [question](https://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context) – Hamza Mohamed Jul 29 '23 at 23:01

1 Answers1

1

The event loop moves only clockwise, it does not move backwards. So in order to go to the timers phase, the event loop has has to go through the check phase which executed the setImmediate callbacks. That is why in a I/o cycle setImmediate will be called first whereas otherwise setTimeout will be called first.

Sagar Chaudhary
  • 1,343
  • 7
  • 21
  • What I'm trying to figure out is - is the setImmediate callback scheduled in next tick or current tick? It only make sense that the callback runs in current tick before Timer phase in next tick, but the node docs says setImmediate callback is scheduled to next tick which is opposite of what lifecycle do. Can anyone explain? – user2734550 Jul 23 '23 at 06:16
  • @Sagar it is not otherwise in the main module, it is not deterministic and can be either, as it depends on libuv initialization unlike the I/O cycle which will have libuv there. – Hamza Mohamed Jul 29 '23 at 23:00