Unlock the full potential of node js setImmediate.

setImmediate runs in the next iteration of the event loop which means node js prioritize what can run immediately such as initialization, assignment, and registering asynchronous codes before calling the setImmediate function.

Let’s take a look at one example

const fs = require('fs');
setImmediate(() => {
  console.log('set immediate runs last');
});

const message = 'this runs first';

fs.readFile("file that doesn't exist", () => {
  console.log('read file runs second');
});

console.log(message);

In the code above set immediate run last after the event loop runs the initialization and console.log and the callback first.

You might also find that the readFile callback runs second unexpectedly, that is because the node js event loop prioritizes IO callbacks, and since I gave a file that doesn’t exist there is no need to wait thus the callback got executed immediately the the readFile is done in the event loop.

What codes run in the event loop? the initialization, the callback, and the console.log run in the event loop while the read file is offloaded to the thread pool. So based on the very first statement, the event loop runs what can be executed Immediately or in other words doesn’t take time such as the initialization, console.log, and the callback of the reading file that doesn’t exist since it finishes very fast.

Now you have an understanding of setImmediate and how it is prioritized in the event loop, how can we use setImmediate to write non-blocking code?

Assume a task that needs a high computation such as finding a sum of n numbers where n can start from 1 to an Infinite number.

Of course, you can just do a for loop to find the sum but imagine where n grows to 10000000000. I would assure you, your application will be stuck for a moment and won’t serve requests.

let sum = 0;
for (let i = 0; i < 10000000000; i++) {
  sum += i;
}

console.log(sum);
console.log("test");

In the above code, you will not see “test” immediately since the event loop is busy computing a large amount of sum. So how can we improve it with setImmediate?

 function sum(n) {
  let sum = 0;
  for (let i = 1; i < n; i++) {
    sum += i;
  }
  return sum;
}

setImmediate(() => {
  console.log(sum(1000000000));
});

console.log('test');

If you run this code, you will see “test” first and then the sum result which is because the event loop prioritizes the other codes and when the sum result is ready it will console log the sum.

The setImmediate is not intended to sum fast but what can it do is not block the main thread so that the other codes can run. setImmediate here is used to call the add function asynchronously so that the event loop will have time to execute other codes.

I used the sum example because it can allow you to understand the setImmediate and the event loop easily and the best scenario to use setImmediate would be to call a function with set Immediate that doesn’t need to be served right away and can block the event loop.

    setImmediate(() => {
        processData(data);
    });

processData here can be anything that takes a long time for example doing high-computing mathematical operations or manipulating arrays of data.

— — — — — — — — — — — — — — — — — —

Follow me on linked in and get the full advanced node js course I will release soon.