A very useful method of scheduling work on the event queue is using the process.nextTick(callback)
function. This function schedules work to be run on the next cycle of the event loop. Unlike the setImmediate()
method, nextTick()
executes before the I/O events are fired. This can result in starvation of the I/O events, so Node.js limits the number of nextTick()
events that can be executed each cycle through the event queue by the value of process.maxTickDepth
, which defaults to 1000
.
The code in Listing 4.3 illustrates the order of events when using a blocking I/O call, timers, and nextTick()
. Notice that the blocking call fs.stat()
is executed first, then two setImmediate()
calls, and then two nextTick()
calls. The output in Figure 4.6 shows that both nextTick()
calls are executed before any of the others, then the first setImmediate()
call, followed by the fs.stat()
call, and then, on the next iteration through the loop, the second setImmediate()
call.
01 var fs = require("fs");
02 fs.stat("nexttick.js", function(err, stats){
03 if(stats) { console.log("nexttick.js Exists"); }
04 });
05 setImmediate(function(){
06 console.log("Immediate Timer 1 Executed");
07 });
08 setImmediate(function(){
09 console.log("Immediate Timer 2 Executed");
10 });
11 process.nextTick(function(){
12 console.log("Next Tick 1 Executed");
13 });
14 process.nextTick(function(){
15 console.log("Next Tick 2 Executed");
16 });