Byeongin Yoon
Byeongin Yoon

Reputation: 4057

Why is process.nextTick() called three times?

confusing diagram of Node event loop

If this picture is right, why is process.nextTick() called three times?

What's the difference?

Upvotes: 0

Views: 691

Answers (2)

Jake Holzinger
Jake Holzinger

Reputation: 6063

process.nextTick() evaluates callbacks up to process.maxDepth

This is a failsafe to prevent the process.nextTick() callback queue from completely hogging the single available thread. In order to still attempt to clear the queue as quickly as possible (e.g. in the next tick) the callbacks are evaluated multiple times in a single event loop.

Imagine process.maxDepth=1 and we call process.nextTick() and setImmidiate() ten times each. All of the callbacks will not be evaluated in a single tick of the event loop. The process.nextTick() callbacks will be evaluated in just over three executions of the event loop, while the setImmidiate() callbacks will take a full ten ticks to completely execute.

Upvotes: 1

Timothy Lee
Timothy Lee

Reputation: 828

Node.js

any time you call process.nextTick() in a given phase, all callbacks passed to process.nextTick() will be resolved before the event loop continues.

There're phrases in event loop ,

before entering next phrase, event loop will execute all process.nextTick callback first.

So it depends on which phase you're calling the process.nextTick

Here's an example

function case1() {
  setImmediate(() => {
    process.nextTick(() => {
        console.log('nextTick')//before going next phase
    })
    console.log('Immediate')
  })
  setTimeout(() => {
    console.log('timer1') //another phase
  })
}

function case2() {
  setImmediate(() => {
    setImmediate(() => {
        console.log('Immediate2') //next event loop
    })
    console.log('Immediate')
  })
  setTimeout(() => {
    console.log('timer1') //another phase
  })
}

then I call them in read file callback to ensure they start at the same phase(poll phase).

const fs = require('fs);

case1 would be

fs.readFile('./package.json', ()=>{
  case1(); 
  //Immediate
  //nextTick
  //timer1
})

case2

fs.readFile('./package.json', ()=>{
  case2()
  //Immediate
  //timer1
  //Immediate2
})

Upvotes: 2

Related Questions