How do you keep the main thread free for setTimeout callbacks?
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.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in setTimeout and Blocking the Main Thread in JavaScript
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.
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.
Still have questions?
Browse all our FAQs or reach out to our support team
