0

Since event loop runs in phases and it enters the timer phase first. Why doesnt setTimeout get executed first since setTimeout has 0 value and the timer should be expired the first time event loop enters timers phase.

1st:

setTimeout(() => {
    console.log('timeout');
  }, 0);
  
  setImmediate(() => {
    console.log('immediate');
  });

Output from running:

timeout
immediate

Output from running again:

immediate
timeout

2nd. This behavior is different than what I see in the following function:

setImmediate(() => {
  console.log("Immediate");
});

setTimeout(() => {
  console.log("Timeout");
}, 0);

process.nextTick(() => {
  console.log("Nexttick");
});

console.log("Hello");

----------It always outputs setTimeout with 0 value before setImmediate which is what I expect before setTimeout with 0 value is an expired timer right from the start.

node AuthenticationController.js
Hello
Nexttick
Timeout
Immediate

node AuthenticationController.js
Hello
Nexttick
Timeout
Immediate
PS C:\Users\vskk0\OneDrive\Documents\nprs-backend\AuthenticationComponent> 

Why does the 2nd function always prints timeout before immediate but not the 1st one?

Vishal
  • 111
  • 6

1 Answers1

0

In the first function the reason sometimes the setTimeout is executed after the setImmediate is because it will check the timer at least once before executing. But you must take into consideration that setTimeout() callback with a 0ms delay is very similar to setImmediate(). The execution order will depend on various factors, but they will be both run in the next iteration of the event loop. I gathered some info that might help you from old questions:

NodeJS - setTimeout(fn,0) vs setImmediate(fn)

the difference between `setTimeout` and `setImmediate`

How is timing of `setImmediate()` and `setTimeout()` bound by the performance of the process?

You might also want to check this from the node.js docs:

https://nodejs.dev/en/learn/understanding-setimmediate/

PTsag
  • 108
  • 2
  • 9