NodeJs event loop

NodeJs event loop_第1张图片
Paste_Image.png

V8有个task queue,IO event,timeout,interval事件会往task queue放入callback,event loop负责在stack为空时,从task queue中取出一个callback执行。

Process.nextTick()

会将callback放入一个next tick queuenext tick queue的执行在stack为空之后,task queue执行下个callback之前执行。

所以nextTick(cb)会在setTimeout(cb, 0)之前执行

Event loop phase

NodeJs event loop_第2张图片
Paste_Image.png

event loop执行时有6个phase

  • timerssetTimeoutsetInterval到期后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被调用了,则进入checkphase,如果setImmediate没被调用,则在poll phase等待callback加入队列。如果timeout触发了,则进入timeoutphase。
  • close callbacks:如果socket或者handle被突然关闭了,close事件会在这个phase触发,否则通过process.nextTick触发

你可能感兴趣的:(NodeJs event loop)