示例工程 08-event-loop-concurrency

08-event-loop-concurrency/04-chunked-long-task/main.js

javascript · 2.6 KB

运行:08 · 长任务分块

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— 把长任务切块,每块之间让出事件循环
// yieldTo 可注入:浏览器优先用 scheduler.yield(),否则用 setTimeout。
 
function defaultYield() {
  const scheduler = globalThis.scheduler;
  if (scheduler && typeof scheduler.yield === 'function') {
    return scheduler.yield();
  }
  return new Promise((resolve) => setTimeout(resolve, 0));
}
 
export function blockingSum(total) {
  let sum = 0;
  for (let i = 0; i < total; i++) sum += i;
  return sum;
}
 
export async function chunkedSum(total, chunkSize, options = {}) {
  const { yieldTo = defaultYield, onChunk } = options;
  if (!Number.isInteger(total) || total < 0) {
    throw new RangeError('total 必须是非负整数');
  }
  if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
    throw new RangeError('chunkSize 必须是正整数');
  }
 
  let sum = 0;
  const chunks = [];
 
  for (let start = 0; start < total; start += chunkSize) {
    const end = Math.min(start + chunkSize, total);
    const chunkStart = performance.now();
    for (let i = start; i < end; i++) sum += i;
    chunks.push(end - start);
    if (typeof onChunk === 'function') onChunk(end - start, performance.now() - chunkStart);
    await yieldTo();
  }
 
  return { sum, chunks };
}
 
export async function interleavingProof() {
  const events = [];
 
  const running = chunkedSum(20, 5, {
    yieldTo: async () => {
      await new Promise((resolve) => setTimeout(resolve, 0));
      events.push('yield');
    },
  });
 
  setTimeout(() => events.push('timer'), 0);
 
  await running;
  return events;
}
 
export async function run(log = console.log) {
  const total = 3_000_000;
 
  const t0 = performance.now();
  const blockingResult = blockingSum(total);
  const blockingMs = performance.now() - t0;
 
  let maxChunkMs = 0;
  const t1 = performance.now();
  const chunked = await chunkedSum(total, 200_000, {
    onChunk: (_size, ms) => {
      maxChunkMs = Math.max(maxChunkMs, ms);
    },
  });
  const chunkedMs = performance.now() - t1;
 
  const interleaved = await interleavingProof();
 
  const rows = [
    ['一次性循环', `${blockingMs.toFixed(1)}ms,结果 ${blockingResult}`],
    ['分块循环', `${chunkedMs.toFixed(1)}ms,${chunked.chunks.length} 块,结果 ${chunked.sum}`],
    ['最长单块', `${maxChunkMs.toFixed(2)}ms`],
    ['分块期间的定时器', interleaved.join(' → ')],
  ];
 
  log('场景 => 结果');
  for (const [label, value] of rows) log(`${label} => ${value}`);
  log('-'.repeat(50));
  log('要点:分块不减少总计算量,只是把长任务拆成多个短任务,让渲染与输入有机会插进来。');
  return rows;
}