What is the event loop?
The event loop is the scheduler that decides what your code runs next. It sits between your JavaScript and the operating system, and it keeps two things moving: a queue of tasks such as timer callbacks and network completions, and a queue of microtasks such as promise reactions.
console.log("1 - sync");
setTimeout(() => console.log("5 - macrotask"), 0);
Promise.resolve().then(() => console.log("3 - microtask"));
queueMicrotask(() => console.log("4 - microtask"));
console.log("2 - sync");The output order is the whole idea in one snippet. Your synchronous code runs to the end of the current task, giving one and two. Then the runtime drains the microtask queue completely, giving three and four. Only then does it take the next task from the task queue, which gives five.
There is one more part of the picture in a browser. After the tasks and the microtasks are empty, the browser may render. It gets a chance to update the page, run the animation frame callbacks, and paint, and then the loop starts again. That is why a page can look frozen while a long synchronous function is running: the loop never gets control back, so no frame is ever painted.
In Node the shape is the same but the sources of tasks differ. The event loop has several phases, and each phase has its own callback queue, with the timers phase and the poll phase being the ones that matter most. The microtask queue behaves identically, which is why the ordering rules you learn in a browser hold in Node too.