Middle+
Tell me about the Event Loop: how does it work, what are microtasks and macrotasks?
sobes.tech AI
Answer from AI
Event Loop is a mechanism in JavaScript that allows asynchronous code to run without blocking the main thread.
It works as follows:
- First, all synchronous code is executed.
- Then, the Event Loop checks the microtask queue and executes them in order.
- After that, macrotasks from the corresponding queue are executed.
Microtasks are tasks with higher priority, executed immediately after the current synchronous code and before macrotasks. Examples of microtasks include promises (Promise.then/catch/finally), MutationObserver.
Macrotasks are tasks with lower priority, executed after microtasks. Examples include setTimeout, setInterval, I/O operations, UI events.
Example:
console.log('start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('end');
The output will be:
start
end
promise
timeout
Because microtasks (promise) are executed before macrotasks (setTimeout).