Sobes.tech
Middle

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:

  1. All code in the call stack is executed.
  2. After the call stack is emptied, all microtasks from the microtask queue are executed.
  3. Then, one macrotask is taken from the macrotask queue and placed in the call stack for execution.
  4. 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
Tell me about the Event Loop: call stack, microtasks… - sobes.tech