setTimeout callbacks execute after Call Stack empties

Theory: "setTimeout callbacks execute after the Call Stack is empty." Practice: I'd never actually put numbers to it until today. ```javascript const start = Date.now(); const delay = (label, ms) =>   console.log(`${label} delayed by ${Date.now() - start - ms}ms`); setTimeout(delay, 0, '0ms', 0); setTimeout(delay, 1, '1ms', 1); setTimeout(delay, 100, '100ms', 100); setTimeout(delay, 300, '300ms', 300); setTimeout(delay, 600, '600ms', 600); for (let i = 0; i < 100000000; i++); // ~100ms blocking work ``` Output: ``` 0ms  → delayed by 103ms 1ms  → delayed by 102ms 100ms → delayed by 3ms 300ms → delayed by 2ms 600ms → delayed by 1ms ``` → 0ms and 1ms were ready instantly, but blocked by the loop → 100ms fired right as the stack cleared → 300ms and 600ms had almost zero extra delay (That ~1-2ms you see even on 300ms/600ms? That's just Event Loop & system overhead — unavoidable.) I've known how the Event Loop works for years. But seeing the actual pattern in milliseconds — that was oddly satisfying. There's a difference between knowing something and feeling it click at a deeper level. #JavaScript #EventLoop #AsyncProgramming

To view or add a comment, sign in

Explore content categories