1. The problem with using timers in node is that it is not accurate. For example, setTimeout() sets a task to be executed after 10ms, but after 9ms, a task takes up 5ms, and when it is the timer's turn again , has been delayed by 4ms.
Okay, that’s all about the timer in node.
2. Look at the code:
Through this example, I think everyone can clearly see what nextTick() is used for. It is mainly used for asynchronous execution.
Looking at the code:
We found that setImmediate is also executed asynchronously. It’s strange
So what is the difference between it and nextTick()?
Look at the code:
Code 1:
Result:
Code 2:
Result:
I found that although the order of the codes is different, the execution result is the same.
It can be found from the results:
The execution priority of the callback function of nextTick() is higher than setImmediate();
process.nextTick() belongs to the idle observer, and setImmediate() belongs to the check observer. In each round of loop inspection, the idle observer precedes the I/O observer, and the I/O observer precedes the check observer. .
In terms of specific implementation, the callback function of process.nextTick() is stored in an array,
The result of setImmediate() is saved in the linked list.
In terms of behavior, process.nextTick() will execute all callback functions in the array in each cycle.
And setImmediate() executes a callback function in the linked list in each cycle.
It can be seen from the execution results: when the first callback function of setImmediate() is executed, the second one is not executed immediately, but enters the next cycle. Press nextTick() again first, setImmediate( ) times. The reason for this design is to ensure that each loop can end quickly and prevent the CPU from occupying too much and blocking subsequent I/O calls.
The above is the information about the difference between the timer nextTick() and setImmediate() in node.js. Do you guys know the difference between them?