-2

While running setTimeout and setImmediate together, Why values are changing for same program when we running it again and again. (setTimeout's timing is 0).

setImmediate(() => {console.log("1")});
setTimeout(()=>{console.log('a')},0)
setTimeout(()=>{console.log('b')},0)
setImmediate(() => {console.log("2")});

While running the program for 1st time output : 1 2 a b

While running the same program for 2nd time output : 1 2 a b

While running the same program for 3rd time output : a 1 2 b

While running the same program for 4th time output : 1 2 a b

While running the same program for 5th time output : a 1 2 b

even it is changing the total order after running n times....

it continuously changing result order when we running it again and again the same program without changing anything.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    `setImmediate()` is not a standard function – Barmar Dec 16 '22 at 20:23
  • @jfriend00 arguably I guess I spent more time reading your various comments complaining about why people waste their time asking these questions than each individual spent investigating it. Maybe the question should become why are you wasting your time on these questions if you don't find it interesting? And honestly, discovering non deterministic behavior in computer programing is worth questioning. – Kaiido Dec 17 '22 at 14:05
  • Curiosity about non-deterministic behavior is a valid reason so my apology for my previous comment. But it shouldn't matter to your programming. If the order of execution of two things matters to your code, you wouldn't rely on the answer to this question to code it - you'd code it to force a specific execution order. FYI, in an environment like nodejs where you have `process.nextTick(fn)`, `setImmediate(fn)` and `Promise.resolve().then(fn)`, I would never use `setTimeout(fn, 0)` anyway as the others are more specific as to what they mean in regards to other things in the event loop. – jfriend00 Dec 17 '22 at 18:49

1 Answers1

3

From the node.js documentation

A 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.

So the relative order of setTimeout() and setImmediate() callbacks is not well specified, it "depends on various factors". You should treat it as unpredictable.

Barmar
  • 741,623
  • 53
  • 500
  • 612