Event Loop Simulator - Problem

Implement a single-threaded event loop simulator that processes tasks from multiple queues with proper priority handling.

Your simulator must handle:

  • Task Queue: Regular tasks (like DOM events, I/O callbacks)
  • Microtask Queue: High-priority tasks (like Promise.then(), queueMicrotask())
  • Timer Queue: Delayed tasks (like setTimeout, setInterval)

The event loop follows JavaScript's execution model:

  1. Execute all available microtasks first
  2. Execute one task from the task queue
  3. Execute all microtasks again
  4. Check for timer tasks that are ready to run
  5. Repeat until all queues are empty

Given a list of operations with timestamps, return the execution order of all tasks.

Input & Output

Example 1 — Basic Event Loop
$ Input: operations = [[0, "task", "A"], [0, "microtask", "B"], [5, "timer", "C", 5]]
Output: ["B", "A", "C"]
💡 Note: At time 0: microtask B executes first (highest priority), then task A. At time 10: timer C is ready and executes.
Example 2 — Multiple Microtasks
$ Input: operations = [[0, "task", "X"], [0, "microtask", "Y"], [0, "microtask", "Z"]]
Output: ["Y", "Z", "X"]
💡 Note: All microtasks (Y, Z) execute first in order, then task X executes.
Example 3 — Timer Scheduling
$ Input: operations = [[0, "timer", "P", 0], [5, "task", "Q"]]
Output: ["P", "Q"]
💡 Note: Timer P with 0 delay executes immediately at time 0, task Q executes at time 5.

Constraints

  • 1 ≤ operations.length ≤ 1000
  • 0 ≤ timestamp ≤ 1000
  • 0 ≤ delay ≤ 100
  • Each task ID is unique

Visualization

Tap to expand
Input OperationsEvent Loop ProcessingExecution Order[0, "task", "A"][0, "microtask", "B"][5, "timer", "C", 5]1Process microtask B2Process task A3Wait for timer C (10ms)4Execute timer CFinal Execution["B", "A", "C"]1. Microtask B first2. Task A second3. Timer C after delayKey Insight:Event loops prioritize microtasks over regular tasks, ensuringcritical operations execute immediately without delay.TutorialsPoint - Event Loop Simulator | Priority Queue Processing
Asked in
Google 35 Meta 28 Microsoft 22 Amazon 18
23.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen