Senior
How is the Event Loop in JavaScript structured? Tell me about micro- and macro-tasks.
sobes.tech AI
Answer from AI
The Event Loop in JavaScript is a mechanism that allows asynchronous code to execute without blocking the main thread.
Main components:
- Call Stack — the stack of calls where the current code is executed.
- Task Queue (macrotasks) — the queue of tasks to be executed after the stack is empty.
- Microtask Queue (microtasks) — the queue of microtasks, which have a higher priority.
When the stack is empty, the Event Loop first executes all microtasks from the microtask queue, then takes one macrotask from the task queue and executes it.
Macrotasks include:
- setTimeout
- setInterval
- setImmediate (in Node.js)
- I/O operations
Microtasks include:
- Promise.then/catch/finally
- process.nextTick (in Node.js)
- MutationObserver
Example:
console.log('script start');
setTimeout(() => {
console.log('setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('promise1');
}).then(() => {
console.log('promise2');
});
console.log('script end');
The output will be:
script start
script end
promise1
promise2
setTimeout
Because microtasks (promises) are executed immediately after the main script, and macrotasks (setTimeout) are executed later.
Thus, the Event Loop ensures the order of asynchronous operations, dividing them into microtasks and macrotasks with different priorities.