Skip to content

QuizNot attempted

Inside an I/O callback

Inside an fs.readFile callback you schedule setTimeout(fn, 0) and setImmediate(fn2). Which runs first?
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • setImmediate, always
  • An I/O callback runs in the poll phase, and the next phase is check (setImmediate)
  • timers only come around on the next loop iteration, so setImmediate wins every time.
  • Not setTimeout always: timers come after check from inside poll.
  • Not random: the race only exists in the main module, where the loop hasn't started.
  • Not until the next readFile: both callbacks are scheduled independently of further I/O.