Skip to the solution
MediumLow-Level DesignAsked in 20247 min read

Build an Async Priority Task Scheduler

3.2k views

The problem

Problem, as an interviewer would state it: "Build a task scheduler that runs queued ASYNC tasks by PRIORITY, not insertion order — a higher-priority task queued later should still run before a lower-priority one that was queued earlier, as long as neither has started yet."

Examples:

Code
scheduler.schedule(lowPriorityTask, 1);
scheduler.schedule(highPriorityTask, 10); // queued SECOND, but should run FIRST

Clarifying questions expected:

  • Can an already-RUNNING task be preempted by a higher-priority one arriving later, or does priority only affect the order of tasks that have not started yet?
  • What real concurrency limit applies — one task at a time, or several running simultaneously?
  • Should two tasks with the SAME priority run in their original insertion order (a stable sort)?

Code / implementation expected: Yes — real, direct, logged proof that tasks queued after an already-started one correctly run in PRIORITY order, not insertion order.

  • 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

7 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 tasks queued after an already-running low-priority task correctly run in priority order (high before medium), not insertion order

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 60 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 nextMedium

Detect a Circular Reference in Any Object or Array Graph

Continue