長いタスクを分割する

ウェブ機能: Scheduler API

重い計算や長いループはメインスレッドをブロックし、ページが応答しなくなる原因となります。これを防ぐには、定期的に制御をブラウザに戻す必要があります。scheduler.yield() API を使用すると、長いタスクを一時停止し、ブラウザでユーザー入力やレンダリングを処理してから続行できます。

長いタスクを分割する

非同期関数内で scheduler.yield() を使用して、作業を分割します。

async function processLargeArray(items) {
  // DO: Set a time-based deadline 50 milliseconds into the future. 50
  // milliseconds is the boundary for when a task becomes a long task.
  let deadline = performance.now() + 50; // 50ms budget

  for (const item of items) {
    // Process the item
    processItem(item);
    
    // MANDATORY: Yield to the main thread periodically to keep the UI
    // responsive. This can be done by checking if the deadline set earlier
    // has been exceeded. When it has been, yield, then reset the deadline
    // another 50 milliseconds into the future.
    if (performance.now() >= deadline) {
      await scheduler.yield();
      deadline = performance.now() + 50;
    }
  }
}

代替戦略

一部のブラウザは scheduler API をサポートしていない場合があります。コードが中断されることなく実行されるようにするには、setTimeout を使用してフォールバックを実装する必要があります。

scheduler.yield() の代替

async function processLargeArrayWithFallback(items) {
  // DO: Set a time-based deadline 50 milliseconds into the future.
  let deadline = performance.now() + 50;

  for (const item of items) {
    processItem(item);
    
    // MANDATORY: Yield to the main thread periodically to keep the UI responsive.
    if (performance.now() >= deadline) {
      // DO: Feature detect scheduler.yield
      if ('scheduler' in window && 'yield' in window.scheduler) {
        await scheduler.yield();
      } else {
        // DO: Fallback to setTimeout for older browsers
        await new Promise(resolve => setTimeout(resolve, 0));
      }
      deadline = performance.now() + 50;
    }
  }
}