Learn the concept
Event Loop & Runtime
The Event Loop is JavaScript's mechanism for handling asynchronous operations. It continuously checks the call stack and task queues, executing callbacks from the microtask queue (Promises) before the macrotask queue (setTimeout, events).
JavaScript is single-threaded but handles async operations through the Event Loop.
Key Components:
Call Stack: Executes synchronous code, one frame at a time
Web APIs / Node APIs: Handle async operations (timers, fetch, I/O)
Task Queue (Macrotasks):
Microtask Queue:
Execution Order:
console.log('1: Start');
setTimeout(() => {
console.log('2: setTimeout');
}, 0);
Promise.resolve()
.then(() => console.log('3: Promise 1'))
.then(() => console.log('4: Promise 2'));
console.log('5: End');
// Output order:
// 1: Start
// 5: End
// 3: Promise 1
// 4: Promise 2
// 2: setTimeout
// Explanation:
// - Sync code runs first (1, 5)
// - Microtasks (Promises) run before macrotasks
// - setTimeout is a macrotask, runs lastBreaking long-running computations into chunks using setTimeout or requestIdleCallback to avoid blocking the UI thread
Using requestAnimationFrame aligned with the event loop rendering phase for smooth 60fps animations
Understanding when to use microtasks vs macrotasks to control the ordering of side effects and UI updates
Build an interactive tool that shows how synchronous code, microtasks, and macrotasks execute in order
Implement a computation that yields to the event loop periodically to keep the UI responsive during heavy processing