Tell me about the Event Loop: call stack, microtasks, 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.
-
Call Stack is the stack of calls where executing functions are stored. When a function is called, it is pushed onto the stack; when it finishes, it is removed.
-
Macrotasks are tasks placed in the event queue. Examples include: setTimeout, setInterval, I/O operations, DOM events.
-
Microtasks are tasks that are executed immediately after the current operation and before the next macrotask. Examples include: promises (Promise.then/catch/finally), process.nextTick (in Node.js).
How the Event Loop works:
- All code in the call stack is executed.
- After the call stack is emptied, all microtasks from the microtask queue are executed.
- Then, one macrotask is taken from the macrotask queue and placed in the call stack for execution.
- The cycle repeats.
This guarantees that microtasks are executed before macrotasks, which is important for the sequence of asynchronous operations.
Example:
console.log('start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('end');
// Output will be:
// start
// end
// promise
// timeout