The JavaScript event loop is the backbone of asynchronous programming in JS. Understanding how microtasks and macrotasks work is essential for writing performant code.
What is the Event Loop? The event loop continuously checks the call stack and the task queue. When the call stack is empty, it takes the first task from the queue and pushes it onto the stack.
Microtasks vs Macrotasks: Promise.then() callbacks go to the microtask queue, while setTimeout callbacks go to the macrotask queue. The event loop processes all microtasks before moving to the next macrotask.
Real-world Example: Consider a scenario where you have both a Promise and a setTimeout:
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// Output: 1, 4, 3, 2
The key takeaway is that microtasks always execute before macrotasks in the same cycle, making Promises more predictable than setTimeout for fine-grained timing control.
Understanding this mechanism helps developers avoid common pitfalls like race conditions and unexpected execution order in complex async flows.