Priority event loop — process events by priority.
1class PriorityQueue {2 constructor() {3 this.items = [];4 }56 enqueue(item, priority) {7 this.items.push({ item, priority });8 this.items.sort((a, b) => a.priority - b.priority);9 }1011 dequeue() {12 return this.items.shift()?.item;13 }1415 get size() {16 return this.items.length;17 }18}1920class PriorityEventLoop {21 constructor() {22 this.queue = new PriorityQueue();23 this.running = false;24 }2526 enqueue(fn, priority = 5) {27 this.queue.enqueue(fn, priority);28 if (!this.running) this.run();29 }3031 run() {32 this.running = true;3334 const processNext = () => {35 if (this.queue.size === 0) {36 this.running = false;37 return;38 }3940 const fn = this.queue.dequeue();41 try {42 fn();43 } catch (err) {44 console.error("Error:", err);45 }4647 process.nextTick(processNext);48 };4950 process.nextTick(processNext);51 }52}5354// Usage55const loop = new PriorityEventLoop();5657loop.enqueue(() => console.log("Low priority"), 10);58loop.enqueue(() => console.log("High priority"), 1);59loop.enqueue(() => console.log("Medium priority"), 5);6061// Output: High, Medium, Low