The Node.js Event Loop, Timers, and process.nextTick()
理解了Node.js Event Loop中的每个 Phases 会执行的 operations 就知道为什么 使用定时器如setTimeout()
设定在 5ms后执行回调函数,但在第3ms时有一个 process.nextTick() 回调函数执行了4ms,则setTimeout()的回调
实际被执行的时间是第7ms。
note: each box will be referred to as a "phase" of the event loop.
What is the Event Loop?
The event loop is what allows Node.js to perform non-blocking I/Ooperations — despite the fact that JavaScript issingle-threaded — by offloading operations to the system kernel whenever possible.
Since most modern kernels are multi-threaded, they can handle multipleoperations executing in the background. When one of these operationscompletes, the kernel tells Node.js so that the appropriate callbackmay be added to the poll queue to eventually be executed. We'll explainthis in further detail later in this topic.
Phases Overview
-
timers: this phase executes callbacks scheduled by
setTimeout()
andsetInterval()
. -
I/O callbacks: executes almost all callbacks with the exception of close callbacks, the ones scheduled by timers, and
setImmediate()
. - idle, prepare: only used internally.
- poll: retrieve new I/O events; node will block here when appropriate.
-
check:
setImmediate()
callbacks are invoked here. -
close callbacks: e.g.
socket.on('close', ...)
.
Between each run of the event loop, Node.js checks if it is waiting for any asynchronous I/O or timers and shuts down cleanly if there are not any.