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.
Code
// 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.