setTimeout and Blocking the Main Thread in JavaScript
A blocked main thread delays setTimeout callbacks. Here is why and how to keep the thread free.
setTimeout and Blocking the Main Thread in JavaScript
setTimeout callbacks only run when the call stack is empty. If you block the main thread, timers are delayed.
The Problem
setTimeout(() => console.log("timer"), 1000); function block() { const start = Date.now(); while (Date.now() - start < 5000) {} } block(); // "timer" logs after 5 seconds, not 1 second
The timer fires at 1 second, but the callback goes to the macrotask queue. The event loop cannot move it to the stack because block is still running.
How to Keep the Thread Free
- Break long tasks into chunks with
setTimeout(cb, 0). - Use Web Workers for heavy computation.
- Use async APIs (fetch, fs.promises).
- Use
requestIdleCallbackfor low-priority work.
The Takeaway
setTimeout callbacks only run when the call stack is empty. Blocking the main thread delays all timers. Keep the thread free by breaking tasks into chunks, using Web Workers, and using async APIs.
Because setTimeout callbacks go to the macrotask queue. The event loop can only move them to the call stack when it is empty. If a synchronous function is blocking the stack, all queued callbacks wait.
Break long tasks into chunks with setTimeout(cb, 0). Use Web Workers for heavy computation. Use async APIs (fetch, fs.promises). Use requestIdleCallback for low-priority work.
Yes. The timer fires at 1 second, but the callback goes to the macrotask queue. The event loop cannot run it while the blocking function is on the stack. The callback runs after 5 seconds.
Yes. Web Workers run on a separate thread. Heavy computation sent to a worker does not block the main thread, so setTimeout callbacks run on time.
Record Date.now() before setTimeout, then measure the actual delay inside the callback. If the actual delay is much larger than the specified delay, the main thread is being blocked.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

