V8有个task queue
,IO event,timeout,interval事件会往task queue放入callback,event loop
负责在stack为空时,从task queue
中取出一个callback执行。
Process.nextTick()
会将callback放入一个next tick queue
,next tick queue
的执行在stack为空之后,task queue
执行下个callback之前执行。
所以nextTick(cb)
会在setTimeout(cb, 0)
之前执行
Event loop phase
event loop执行时有6个phase
-
timers
:setTimeout
和setInterval
到期后callback会在这个phase执行 -
I/O callbacks
:
This phase executes callbacks for some system operations such as types of TCP errors. For example if a TCP socket receives ECONNREFUSED when attempting to connect, some *nix systems want to wait to report the error. This will be queued to execute in the I/O callbacks phase
-
idle, prepare
:内部使用 -
poll
: 如果poll队列不为空,依次执行poll队列中的callback。如果poll队列为空,如果setImmediate
被调用了,则进入check
phase,如果setImmediate
没被调用,则在poll phase等待callback加入队列。如果timeout触发了,则进入timeout
phase。 -
close callbacks
:如果socket或者handle被突然关闭了,close
事件会在这个phase触发,否则通过process.nextTick
触发