Middle+
Tell about Event Loop: in what order are synchronous code, microtasks, and macrotasks executed?
sobes.tech AI
Answer from AI
Event Loop is a mechanism in JavaScript that manages the execution of code, event handling, and asynchronous operations.
Order of execution:
- Synchronous code executes immediately, in order, on the main thread.
- After synchronous code executes, microtasks (microtasks) are run. Microtasks include, for example, promises (
Promise.then),process.nextTickin Node.js. - Then, macrotasks (macrotasks) are executed, such as event handlers, timers (
setTimeout,setInterval), network requests.
The cycle repeats: after each macrotask, the Event Loop checks the microtask queue and executes all microtasks before moving on to the next macrotask.
Example:
console.log('Synchronous code');
setTimeout(() => console.log('Macrotask (setTimeout)'), 0);
Promise.resolve().then(() => console.log('Microtask (Promise)'));
console.log('Synchronous code 2');
The output will be:
Synchronous code
Synchronous code 2
Microtask (Promise)
Macrotask (setTimeout)
This demonstrates that microtasks are executed immediately after synchronous code, but before macrotasks.