Question presented to candidate: "If I call setTimeout with a delay of 0, does the callback run immediately? What is actually happening under the hood?"
What a strong answer should cover:
- setTimeout(fn, 0) does NOT run fn synchronously or immediately -- it schedules fn as a macrotask, which always waits at minimum for the rest of the current synchronous code to finish.
- Before that macrotask can run, the entire microtask queue must be completely empty -- even microtasks that get added after the setTimeout call still run first.
- "0ms" is a request, not a guarantee -- both browsers and Node.js apply a real minimum delay floor, and a negative or missing delay is clamped the same way a 0 is.
- Browsers additionally clamp nested setTimeout chains (calling setTimeout from inside a setTimeout callback, 5+ levels deep) to a minimum of 4ms, per the HTML spec -- a rule Node.js does not implement the same way.
- Practical use: setTimeout(fn, 0) is a common way to defer work to "the next macrotask turn," letting the browser repaint or letting other pending events process, especially for breaking up long synchronous work.
Clarifying questions expected:
- "Are we talking about a single setTimeout(0) call, or a chain of nested ones -- the nesting case has an extra clamping rule in browsers."
Code / implementation expected: Yes -- a short, runnable snippet showing a setTimeout(0) genuinely waiting for pending microtasks before running.