Middle+
How does the Event Loop work? What are macro-tasks and micro-tasks? What belongs to micro-tasks?
sobes.tech AI
Answer from AI
Event Loop is a mechanism in JavaScript that allows executing code, handling events, and performing sub-tasks asynchronously without blocking the main thread.
Macrotasks are the main tasks placed in the event queue, for example:
- Event handlers (click, load)
- setTimeout, setInterval
- Network requests
Microtasks are tasks with higher priority, executed immediately after the current operation and before the next macrotask. They include:
- Promise.then/catch/finally
- MutationObserver
After executing the current script, the Event Loop first executes all microtasks, then proceeds to the next macrotask.
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
This shows that microtasks (promises) are executed before macrotasks (setTimeout).