setTimeout, setInterval & Timers Interview Q&A
JS جاوااسکریپت

setTimeout, setInterval & Timers Interview Q&A

Minimum delays, clearing timers, and how timers interact with the event loop.

BugCast Admin··۵ دقیقه مطالعه

Timers look simple but tie directly to the event loop and macrotask queue. Cleanup and delay accuracy are common follow-up topics.

Common Interview Questions

Q: Is setTimeout(fn, 0) immediate?

Answer: No — it schedules a macrotask after the current call stack clears and microtasks run. Minimum delay is clamped (often 4ms in browsers after nesting).

Q: setInterval vs recursive setTimeout?

Answer: setInterval fires on a fixed schedule regardless of handler duration, which can overlap. Recursive setTimeout waits for completion plus delay — safer for async work.


function poll() {
  doWork().finally(() => setTimeout(poll, 1000));
}

Q: How do you clear timers in React?

Answer: Return cleanup from useEffect to clear timeouts/intervals and prevent state updates on unmounted components.


useEffect(() => {
  const id = setTimeout(() => setReady(true), 300);
  return () => clearTimeout(id);
}, []);

Q: setTimeout return value?

Answer: A numeric timer ID (or object in Node) passed to clearTimeout/clearInterval to cancel scheduled callbacks.

Key Points for Interviews

  • Timers are macrotasks — after microtasks

  • Always clear timers on unmount or cancel flows

  • Do not trust interval accuracy under heavy main-thread load

  • requestAnimationFrame for visual updates, not setInterval

  • Node timers behave similarly but see setImmediate differences

#timers#event-loop#interview

مطالب مرتبط