JavaScript
Event Loop
The Event Loop is a mechanism that controls the order of code execution in JavaScript. It allows single-threaded JS to process asynchronous tasks, ensuring continuous program execution without blocking.
Core Idea
- JavaScript works in one thread, where the call stack (Call Stack) is executed.
- Asynchronous operations (timers, I/O, promises) are handled by external APIs of the environment (browser, Node.js).
- Upon completion, the operation adds a callback to the corresponding task queue.
- The Event Loop monitors the stack: when it is empty, it takes a task from the queue and places it in the stack for execution.
Execution Order and Priority
- All synchronous code (code in the call stack) is executed.
- When the stack is empty, the Event Loop takes one macrotask from the queue and executes it.
- After that, all microtasks are executed (the queue is cleared completely).
- Then the browser can perform frame rendering.
- The cycle repeats.
If new microtasks are created during the execution of microtasks — they are also executed in the same pass until the queue is empty.
Microtasks
Promise.then,.catch,.finallyqueueMicrotask()MutationObserver- (Node.js)
process.nextTick()— executed earlier than regular microtasks
Macrotasks
setTimeout,setIntervalsetImmediate(Node.js)postMessage,MessageChannel- DOM event callbacks
requestAnimationFrame— called between microtask clearing and frame rendering, formally does not belong to any category.
Microtask vs Macrotask
| Characteristic | Microtask | Macrotask |
|---|---|---|
| Examples | Promise.then, queueMicrotask, MutationObserver | setTimeout, setInterval, DOM events |
| Source | Internal JS APIs | External environment APIs (browser / Node.js) |
| Priority | Executed immediately after the current task, before rendering | Executed one per iteration of the Event Loop |
| Usage | Short operations requiring immediate processing | Asynchronous operations, timers, events |
| Sequence | All microtasks are executed before the next macrotask | After clearing microtasks and possible rendering |
In other words, microtasks are executed earlier than macrotasks — they create an internal priority cycle within one step of the Event Loop.
Key Ideas
- The Event Loop coordinates the execution of synchronous and asynchronous code.
- Microtasks are always executed before the next macrotask.
- Promises and timers fall into different queues and are processed at different stages of the cycle.
- This mechanism guarantees smooth, non-blocking operation of JS applications.