微任务优先级队列与事件循环节流
利用 queueMicrotask 与自定义微任务调度器,构建可抢占的微任务优先级系统,避免长微任务阻塞事件循环。 · 难度:入门 · +10XP
微任务优先级队列与事件循环节流
Node.js 的微任务队列(Promise、queueMicrotask)是 FIFO 且不可中断。本教程设计一个 PriorityMicrotaskQueue,在微任务执行前检查预计耗时,若超过阈值则将其降级并插入到下一次事件循环(通过 setImmediate)。你将学习通过 AsyncHook 拦截微任务创建、利用 performance.now() 动态测量执行时间,并实现一个可配置的节流器来防止事件循环滞后。
class PriorityMicrotaskQueue {
constructor() {
this.queues = { high: [], normal: [], low: [] };
this.threshold = 5; // ms
}
enqueue(fn, priority = 'normal') {
this.queues[priority].push(fn);
this.schedule();
}
schedule() {
if (this.running) return;
this.running = true;
queueMicrotask(() => {
const start = performance.now();
while (this.queues.high.length) {
const task = this.queues.high.shift();
task();
if (performance.now() - start > this.threshold) {
setImmediate(() => this.processRemaining());
break;
}
}
this.running = false;
});
}
}