拆分長時間任務

網頁功能: 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;
    }
  }
}