This script is from a Nodejs introducing book. This part is about the event loop of Javascript.
const sleep_st = (t) => new Promise((r) => setTimeout(r, t));
const sleep_im = () => new Promise((r) => setImmediate(r));
(async () => {
setImmediate(() => console.log(1));
console.log(2);
await sleep_st(0);
setImmediate(() => console.log(3));
console.log(4);
})();
The two possible outputs are "2 4 1 3" and "2 1 4 3".
I expect the outputs are always consistent.
2
Answers
The code produces a different order of numbers each time because of the interplay between the JavaScript event loop, microtasks, and macrotasks, which introduces non-deterministic behavior.
Order of Execution
Step-by-Step Execution:
Start Execution:
Macrotask: sleep_st(0) Resolves:
Inside the Async Function:
Event Loop Execution:
Why the Order Changes:
Similar to sleep_st, you can use a promise wrapping setImmediate and await it. In this example the output is always 1 2 3 4. I faked setImmediate for the example since it doesn’t exist in browsers.