Skip to the solution
HardLow-Level DesignAsked in 20246 min read

Microtask scheduler task runner

3.7k views

The problem

Problem, as an interviewer would state it: "Build a task runner that batches multiple pushed tasks and runs them all together as MICROTASKS — the whole batch must run before any real, already-scheduled macrotask (like a setTimeout), even one scheduled earlier."

Examples:

Code
setTimeout(() => console.log("macrotask"), 0);
runner.push(() => console.log("microtask 1"));
runner.push(() => console.log("microtask 2"));
// real order: microtask 1, microtask 2, THEN macrotask -- despite setTimeout being called first

Clarifying questions expected:

  • Should multiple pushes made synchronously in the same tick be batched into ONE real microtask, or does each get its own separate microtask?
  • Does the runner need to guarantee tasks run in the order they were pushed?
  • What is the real, defining difference between a microtask and a macrotask that makes this ordering guaranteed?

Code / implementation expected: Yes — real, direct proof against an actual setTimeout(0) scheduled BEFORE the runner's own tasks, confirming the microtask batch genuinely runs first.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: two microtasks pushed after a real setTimeout(0) call still run before that macrotask fires

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 128 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Infinite scroll list simulator

Continue