1

Code Snippet-1

setTimeout(() => console.log("setTimeout1"));
setTimeout(() => console.log("setTimeout2"));
setImmediate(() => console.log("setImmediate1"));
setImmediate(() => console.log("setImmediate2"));

Code Snippet-2

setTimeout(() => console.log("setTimeout1"));
setTimeout(() => console.log("setTimeout2"));
setImmediate(() => console.log("setImmediate1"));
setImmediate(() => console.log("setImmediate2"));
console.log('hey');

Snippet 1's outputs, when run multiple times:

> setTimeout1, setTimeout2, setImmediate1, setImmediate2
> setImmediate1, setImmediate2, setTimeout1, setTimeout2
> setTimeout1, setImmediate1, setImmediate2, setTimeout2

Snippet 2 always returns in the following order:

> hey, setTimeout1, setTimeout2, setImmediate1, setImmediate2

I read about setImmediate() and setTimeout() and understood that the results might vary, but how does adding a console.log() in Snippet-2 return the same output every time?

Node: v16.18.0

RedPotato
  • 37
  • 5
  • You need to understand **async** call with javascript, your code is fine. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – Taher Ben sassi Dec 25 '22 at 12:18
  • FYI: asynchronous code/function is harder to work with because it'll execute in a different order every single time potentially which means that you have to make sure that your code will work no matter which path it takes whether it executes. – Taher Ben sassi Dec 25 '22 at 12:27
  • @TaherBensassi Then why is there no change when I run Snippet 2? – RedPotato Dec 25 '22 at 14:09
  • "*when run multiple times*" - how exactly do you run the snippet? Put the whole thing in a file, run it as a script? Or were you running it from a loop? Or from the REPL? – Bergi Dec 25 '22 at 19:26
  • 1
    @TaherBensassi This has absolutely nothing to do with `async` functions – Bergi Dec 25 '22 at 19:26
  • 1
    @Bergi I created a `test.js` file and manually ran it multiple times from the terminal using `node test.js`. – RedPotato Dec 25 '22 at 19:49

0 Answers0