Microtask Batching For Batched Updates

Batch many rapid updates into one flush by scheduling work on the microtask queue so renders and network calls stay coalesced.

JavascriptResilience

Code

javascriptsnippet
27 lines
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');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

What the code does

What another module actually calls is the functions scheduleFlush and enqueue — everything else is wiring.

Points of care

  • The guard scheduled stops the pass immediately with an early return when its condition holds.

Using it

The primary signature is function scheduleFlush()

The demo output is labeled (flushed, synchronous enqueue done), so each line traces straight back to the statement that printed it.

Key statements

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

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `scheduleFlush`, `enqueue` at load time.