setTimeout() vs setImmediate() in Node.js

setTimeout() method is similar to the window.setTimeout() method in JavaScript. It takes two arguments . First argument is a function, the second is the time value. The function passed as argument will execute after the given time.

var initialTime = Date.now();

setTimeout(() => {
    var final Time = Date.now();
    console.log(`time difference : ${finalTime - initialTime}`);
},1500);

In the above example we are storing the initial time before setTimeout is called. The final time is stored after the argument function executes. Using console.log we are printing time taken for the execution. We can also add a third optional argument. Third argument will be passed to the function.

var initialTime = Date.now();

setTimeout((t) => {
    var finalTime = Date.now();
    console.log(`time difference : ${finalTime - t}`);
},1500,initialTime);

setImmediate method executes a function just after the next code blocks after setImmediate function. In other words the method will execute a function at the end of the event loop cycle. This method takes the function to be executed as the first  argument. You can pass extra arguments.

console.log('before....');

setImmediate((arg) => {
  console.log(`executing....${arg}`);
}, '!!!!');

console.log('after 1....');
console.log('after 2.....');

The output of this example is the following.


before....

after 1....

after 2.....

executing....!!!!


It will return one immediate object. This object can be used to cancel a scheduled immediate using clearImmediate() method.