What is the event loop?
The event loop is the part of JavaScript that decides what your code runs next. It sits between your JavaScript and the operating system, and it keeps two queues moving. The first queue holds tasks, such as timer callbacks and finished network requests. The second queue holds microtasks, such as promise reactions.
console.log('1 - sync');
setTimeout(function () {
console.log('5 - macrotask');
}, 0);
Promise.resolve().then(function () {
console.log('3 - microtask');
});
queueMicrotask(function () {
console.log('4 - microtask');
});
console.log('2 - sync');The order of the output is the whole idea in one small example. Your synchronous code runs to the end of the current task, which gives you one and two. Then the runtime empties the microtask queue completely, which gives you three and four. Only after that does it take the next task from the task queue, which gives you five.
There is one more part of the picture in a browser. After the tasks and the microtasks are both empty, the browser may render. It gets a chance to update the page, to run the animation frame callbacks, and to paint the screen, 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 are different. The event loop there has several phases, and each phase has its own callback queue. The timers phase and the poll phase are the two that matter most. The microtask queue behaves in exactly the same way, which is why the ordering rules that you learn in a browser also hold in Node.