0

I am learning Node.js and having a very hard time in understanding the working of setImmediate() and process.nextTick(). In order to understand the concepts clear, I have three programs, one plain, simple node.js program, one using setImmediate() and one using process.nextTick(). Apparently all three behaving in different way. It would be of great help if anyone explain how these programs differ in operation under the hood and explain the significance of using both timers for effective Node.js programming.

Program 1: (without setImmediate() and process.nextTick())

var fs = require('fs');

function logCar(car, callback){
  console.log("Saw a %s", car);
  if(cars.length){
    callback();
  }
}
function logCars(cars){
  var car = cars.pop();
  logCar(car, function(){
    logCars(cars);
  });
}
var cars = ["Ferrari", "Porsche", "Bugatti", 
            "Lamborghini", "Aston Martin"];
logCars(cars);

var fileCheck = function(){
    console.log('entered file operation');
    fs.stat("fileio.js", function(err,stats){
    if(stats)
    console.log("file exists");
    });
    }
    
    fileCheck();

Result:

Saw a Aston Martin
Saw a Lamborghini
Saw a Bugatti
Saw a Porsche
Saw a Ferrari
entered file operation
file exists

Program 1: (with setImmediate())

var fs = require('fs');

function logCar(car, callback){
  console.log("Saw a %s", car);
  if(cars.length){
    setImmediate(function(){
      callback();
    });
  }
}
function logCars(cars){
  var car = cars.pop();
  logCar(car, function(){
    logCars(cars);
  });
}
var cars = ["Ferrari", "Porsche", "Bugatti", 
            "Lamborghini", "Aston Martin"];
logCars(cars);

var fileCheck = function(){
    console.log('entered file operation');
    fs.stat("fileio.js", function(err,stats){
    if(stats)
    console.log("file exists");
    });
    }
    
    fileCheck();

Result:

Saw a Aston Martin
entered file operation
Saw a Lamborghini
file exists
Saw a Bugatti
Saw a Porsche
Saw a Ferrari

Program 2: (with process.nextTick())

var fs = require('fs');

function logCar(car, callback){
  console.log("Saw a %s", car);
  if(cars.length){
    process.nextTick(function(){
      callback();
    });
  }
}
function logCars(cars){
  var car = cars.pop();
  logCar(car, function(){
    logCars(cars);
  });
}
var cars = ["Ferrari", "Porsche", "Bugatti", 
            "Lamborghini", "Aston Martin"];
logCars(cars);

var fileCheck = function(){
    console.log('entered file operation');
    fs.stat("fileio.js", function(err,stats){
    if(stats)
    console.log("file exists");
    });
    }
    
    fileCheck();

Result:

Saw a Aston Martin
entered file operation
Saw a Lamborghini
Saw a Bugatti
Saw a Porsche
Saw a Ferrari
file exists
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Meeran Mohideen
  • 169
  • 1
  • 3
  • 14
  • 2
    See [**What is the difference between synchronous and asynchronous programming (in node.js)**](http://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node) and [**setImmediate vs. nextTick**](http://stackoverflow.com/questions/15349733/setimmediate-vs-nexttick). Please let me know if these do not answer your question. – Qantas 94 Heavy Mar 03 '15 at 11:34
  • setImmediate() postpones the current event loop (logCars(cars)) giving importance to the I/O thread to complete and comes back to the current event loop. process.nextTick() places the I/O thread to start immediately after the end of the current event loop. Am I right ? . If wrong please correct me. – Meeran Mohideen Mar 03 '15 at 12:10
  • Well it doesn't really "postpone" it, at each point in the event loop it sees what it needs to run and executes it then. Apart from that, it seems good to me. – Qantas 94 Heavy Mar 03 '15 at 12:21
  • So basically one should use setImmediate() when he cares about any I/O operation running behind which he doesnt want to get starved... ? – Meeran Mohideen Mar 03 '15 at 12:34
  • If you're running I/O behind the scenes and that's meant to take priority, yes use `setImmediate`. However, note that your own code will run slower as a result. – Qantas 94 Heavy Mar 03 '15 at 12:37
  • Does this answer your question? [setImmediate vs. nextTick](https://stackoverflow.com/questions/15349733/setimmediate-vs-nexttick) – ggorlen May 25 '22 at 00:10

1 Answers1

4

Callbacks deferred with process.nextTick() run before any other I/O event is fired.

With setImmediate(), the execution is queued behind any I/O event that is already in the queue.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
user3085414
  • 122
  • 2
  • Is this a quote from Node.js Design Patterns, by Mario Casciaro, based on the citation in [this answer](https://stackoverflow.com/a/42030923/6243352)? If so, you should cite it, or, better yet, just close the question as a dupe of that one, since that's the canonical thread and has way more information in it than this one. – ggorlen May 25 '22 at 00:10