Simple answer:
setImmediate runs on the next tick.
Details:
setImmediate and setTimeout both run in different phases on the event loop.
That is why when setTimeout is set with zero delay it will not run immediately. Use setImmediate which always run on the next tick of the event loop.
but
process.nextTick basically does not care about phases of event loop. The callback you assign to this method will get executed after the current operation is complete and before event loop continues.
The document you linked has a very good explanation about the differences. I'll just grab your attention to few points here.
In setimmediate-vs-settimeout the order of call is nondeterministic UNLESS they are scheduled within an I/O cycle like below example.
Now add the process.nextTick to the example
const fs = require('fs');
// I/O cycle
fs.readFile(__filename, () => {
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
});
process.nextTick(() => {
console.log('nextTick')
})
Output:
nextTick
immediate
timeout
If you run the above code whatever is in process.nextTick function will get executed first. The reason is, it runs before event loop continues. Remember, both setTimeout and setImmediate are event loop related but not process.nextTick.
Be very careful how you use the process.nextTick. You can end up in bad situations if you are not using it properly.