← 中文资源

简体中文版本

微任务批量合并更新

把高频更新排进微任务队列合并一次 flush:连续入队只触发一次渲染/请求,同步代码跑完立即执行。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

synchronous enqueue done
flushed 4 updates: a,b,c,d

实现说明

微任务批量合并更新以函数 scheduleFlush、enqueue为骨架。

使用要点

  • 守卫 scheduled 满足时靠提前的 return 短路流程。
  • 每一步打印都带着自己的标签:flushed、synchronous enqueue done。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 scheduleFlush、enqueue。

签名一览:function scheduleFlush()

核心语句

queueMicrotask(() => {
  scheduled = false;
  const batch = [...pending];
  pending.clear();
  console.log('flushed', batch.length, 'updates:', batch.join(','));
});
const pending = new Set();

代码示例

const pending = new Set();
let scheduled = false;

function scheduleFlush() {
  if (scheduled) return;
  scheduled = true;
  // 微任务:当前同步代码跑完立刻执行一次,不等到下一帧
  queueMicrotask(() => {
    scheduled = false;
    const batch = [...pending];
    pending.clear();
    console.log('flushed', batch.length, 'updates:', batch.join(','));
  });
}

function enqueue(id) {
  pending.add(id);
  scheduleFlush();
}

// 连续 5 次入队只触发一次 flush
enqueue('a');
enqueue('b');
enqueue('c');
enqueue('a');
enqueue('d');
console.log('synchronous enqueue done');