What happens if nextTick runs when waiting in Polling phase?

22 Views Asked by At

The nextTick and microTask occur on the tick that moves phase by phase.

This means that if the tick does not occur, nextTick or microTask will not occur.

So if Timer, Pending, etc. don't have Callback, Polling is in a waiting state, and nextTick doesn't happen forever, is that correct?

2

There are 2 best solutions below

2
anarchomeritocrat On

If tick stuck on the some code, this point on architecture problem, like inner infinite loop, or operations, which consume a lot of CPU, or blocking operations, like a syncronously reading of a huge file. JS have not waiting operations, or pause logic. You can understand that, using next diagram from here:

   ┌───────────────────────────┐
┌─>│           timers          │ 
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks     │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare       │
│  └─────────────┬─────────────┘      ┌───────────────┐
│  ┌─────────────┴─────────────┐      │   incoming:   │
│  │           poll            │<─────┤  connections, │
│  └─────────────┬─────────────┘      │   data, etc.  │
│  ┌─────────────┴─────────────┐      └───────────────┘
│  │           check           │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤      close callbacks      │
   └───────────────────────────┘

Each phase of event loop means that node.js (by fact libuv) just a looking up, is some timer expired?, is some condition for pending callback satisfied?, and so on, and every thats phases checks are non blocking, unlike some havy, or blocking logic, which can be started in a result of that check

If some stuck happence, I recommend next solutions:

For infinite loops, try to refactor code to avoid them, because, by fact, you code allready works in the infinite event loop, so, use nextTick, or setImmediate for go away from blocking code style

For blocking operations (working with network, filesystem, databases, etc), refactor logic to asyncronouse code style

For operations, which consume a lot of CPU, use child_process and move havy logic in a separate threads

0
Kaiido On

The nextTick or microtask will be queued from somewhere, which will be one of the phases of the event-loop. So their callback will be called right after this somewhere, in the same phase.

Remember that nextTick isn't one of the phases, to quote the docs:

This is because process.nextTick() is not technically part of the event loop. Instead, the nextTickQueue will be processed after the current operation is completed, regardless of the current phase of the event loop. Here, an operation is defined as a transition from the underlying C/C++ handler, and handling the JavaScript that needs to be executed.