Long Batches Yield With setImmediate

Chunk CPU-heavy loops and await a setImmediate between slices so pending callbacks interleave and the process never blocks for the whole run.

TypescriptCli Tooling

Code

typescriptsnippet
21 lines
// CPU 密集批次分片:每片之间 setImmediate 让出事件循环(yield),
// I/O 与定时器回调得以穿插,进程不再长时间阻塞
const BATCH = 40;
const items = Array.from({ length: 120 }, (_, i) => i + 1);

async function processAll(items: number[]): Promise<number> {
  let checksum = 0;
  for (let start = 0; start < items.length; start += BATCH) {
    for (const n of items.slice(start, start + BATCH)) {
      checksum = (checksum + n * 31) % 1_000_003;
    }
    console.log(`chunk ${start / BATCH + 1}: checksum ${checksum}`);
    // 让出事件循环(yield):pending 的回调在下一片之前执行
    await new Promise((resolve) => setImmediate(resolve));
  }
  return checksum;
}

const final = await processAll(items);
console.log(`final checksum: ${final}`);

Inside the snippet

Structurally, expect the function processAll and nothing else.

The core work runs in nested loops — outer for (let start = 0; start < items.length; start += BATCH), inner for (const n of items.slice(start, start + BATCH)). The async parts await their results, which keeps ordering predictable.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: async function processAll(items: number[])

Look for the chunk $, final checksum: $ prefixes when the file runs; they tie each line to its step.

Core lines

await new Promise((resolve) => setImmediate(resolve));
const items = Array.from({ length: 120 }, (_, i) => i + 1);
const final = await processAll(items);

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `processAll` at load time.