JavaScript is **single-threaded** — one operation at a time. The **event loop** enables concurrency via queues: (1) synchronous code runs on the **call stack**, (2) **microtask queue** (Promise .then, queueMicrotask) drains COMPLETELY after each stack task, (3) **macrotask queue** (setTimeout, setInterval) runs one task at a time.
1Understanding Event Loop
JavaScript is single-threaded — one operation at a time. The event loop enables concurrency via queues: (1) synchronous code runs on the call stack, (2) microtask queue (Promise .then, queueMicrotask) drains COMPLETELY after each stack task, (3) macrotask queue (setTimeout, setInterval) runs one task at a time.
Microtasks (Promises) always run before the next macrotask (setTimeout). This is why Promise.resolve().then() runs before setTimeout(fn, 0).
console.log('1: Start');
setTimeout(() => console.log('5: setTimeout'), 0);
Promise.resolve()
.then(() => console.log('3: Promise 1'))
.then(() => console.log('4: Promise 2'));
console.log('2: End');
// Output order: 1, 2, 3, 4, 52Practical Example
Here is a real-world application of Event Loop showing how it is used in production JavaScript code.
// Blocking the event loop
function longTask() {
const start = Date.now();
while (Date.now() - start < 3000) {} // blocks for 3 seconds!
console.log('Done (but UI was frozen!)');
}
// Better: use Web Workers for CPU tasks
const worker = new Worker('./compute.js');
worker.postMessage({ task: 'heavyComputation' });3Best Practices
Follow these guidelines when working with Event Loop:
1. Don't block the event loop with long synchronous code
2. Use Web Workers for CPU-intensive tasks
3. Use requestAnimationFrame for smooth animations
Tip: Microtasks (Promises) always run before the next macrotask (setTimeout). This is why Promise.resolve().then() runs before setTimeout(fn, 0).
console.log('1: Start');
setTimeout(() => console.log('5: setTimeout'), 0);
Promise.resolve()
.then(() => console.log('3: Promise 1'))
.then(() => console.log('4: Promise 2'));
console.log('2: End');
// Output order: 1, 2, 3, 4, 5