拆分长任务

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