Event Loop
JavaScript is single-threaded but handles async operations via the event loop.
How It Works
Three components work together:
- Call Stack — where synchronous code runs (LIFO)
- Web API — handles async ops (
setTimeout,fetch, DOM events) - Callback Queue — waits for the stack to empty
Example
console.log('1')
setTimeout(() => console.log('2'), 0)
console.log('3')
// Output: 1, 3, 2
Even with 0ms delay, setTimeout goes through the Web API and callback queue, so it runs after the synchronous code.
Microtasks vs Macrotasks
console.log('start')
setTimeout(() => console.log('setTimeout'), 0) // macrotask
Promise.resolve().then(() => console.log('promise')) // microtask
console.log('end')
// Output: start, end, promise, setTimeout
Microtasks (Promises) run before macrotasks (setTimeout, setInterval).
Practical Impact
// This is non-blocking:
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => console.log(data))
console.log('This runs while fetch is pending!')