0

Official node docs explain the following:

the nextTickQueue will be processed after the current operation completes, regardless of the current phase of the event loop.

With this in mind, I tested process.nextTick() the following way:

const heapdump = require('heapdump');

let count = 0;

function snapshot(){
    setTimeout(() => heapdump.writeSnapshot(), 5000)
}

process.nextTick(snapshot);

while(true){
    count++
    console.log(count);
}

My intention is to have process.nextTick(snapshot); forcefully include the snapshot function into the event loop, calling itself during the infinite while loop.

Why does this not happen?

Clem
  • 3
  • 4
  • Take a look at [this answer](https://stackoverflow.com/a/16504980/504930) on how to achieve what you wanted to with this example. – devius Jan 26 '18 at 10:48

1 Answers1

0

It doesn't happen because node's event loop is single threaded, so the "next tick" will only happen after the infinite while is finished processing, which, as you may have guessed, is never.

This happens because node.js can only perform non-blocking I/O operations in this single thread, but synchronous code is executed, well synchronously, and it does block execution of the event loop.

So, in your example, the event loop is blocked waiting for the while loop to finish, never reaching the "next tick", or the next phase.

devius
  • 2,736
  • 22
  • 26
  • Ahh I didn't realize that synchronous code entirely blocked the event loop. Good to know. Thank you! – Clem Jan 26 '18 at 13:17