React—Learning--调度与时间片

1,401 阅读9分钟

一 前言

首先带着疑问🤔️来看react中调度模式:

  1. react异步调度产生的原因;
  2. 什么是时间分片;
  3. React 如何模拟 requestIdleCallback?
  4. 调度流程?
  5. schduler如何实现中断、恢复、判断这个任务有没有执行完?

二 时间分片

在浏览器中首先有一个问题,GUI 渲染线程和 JS 引擎线程是相互排斥的,比如开发者用 js 写了一个遍历大量数据的循环,在执行 js 时候,会阻塞浏览器的渲染绘制,给用户直观的感受就是卡顿。为了解决问题React 将更新,交给浏览器自己控制,如果浏览器有绘制任务那么执行绘制任务,在空闲时间执行更新任务,就能解决卡顿问题了。

时间分片 / 时间切片

浏览器在每次执行一次时间循环都会做如下事情:

一个task(宏任务) -- 队列中全部job(微任务) -- requestAnimationFrame -- 浏览器重排/重绘 -- requestIdleCallback

在此后,如果没有其他事件,浏览器会进入休息时间,那么有的一些不是特别紧急 React 更新,就可以执行了。

React是怎么知道浏览器会有空闲时间呢?

requestIdleCallback,是谷歌浏览器提供的一个 API, 在浏览器有空余的时间,浏览器就会调用 requestIdleCallback 的回调。首先看一下 requestIdleCallback的基本用法:

requestIdleCallback(callback,{ timeout })
  • callback 回调,浏览器空余时间执行回调函数。
  • timeout 超时时间。如果浏览器长时间没有空闲,那么回调就不会执行,为了解决这个问题,可以通过 requestIdleCallback 的第二个参数指定一个超时时间。

模拟requestIdleCallback

但是 requestIdleCallback 目前只有谷歌浏览器支持 ,为了兼容每个浏览器,React需要自己实现一个 requestIdleCallback ,React中采用了task(宏任务)MessageChannel方式实现

MessageChannel 接口允许开发者创建一个新的消息通道,并通过它的两个 MessagePort 属性发送数据。

  • MessageChannel.port1 只读返回 channel 的 port1 。
  • MessageChannel.port2 只读返回 channel 的 port2 。

让我们看一下基于 MessageChannel 是如何工作的:

const channel = new MessageChannel();
const port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;

function requestHostCallback(callback) {
  scheduledHostCallback = callback;
  if (!isMessageLoopRunning) {
    isMessageLoopRunning = true;
    port.postMessage(null);
  }
}
  • 实例化 MessageChannel,并创建两个 Port
  • 设置 port1 的 handle 为 performWorkUntilDeadline
  • requestHostCallback 将发送消息,触发 performWorkUntilDeadline

这里留下个疑问🤔 --- performWorkUntilDeadline这个函数做了什么

三 调度流程

React发生一次更新,会统一走ensureRootlsScheduled(调度应用)。

V18版本Concurrent模式会有低优先级--useTransition

  • 对于正常更新会走performSyncWorkOnRoot逻辑,最后在workLoopSync。
  • 对于低优先级的异步更新会走performConcurrentWorkOnRoot逻辑,最后会走workLoopConcurrent。

如下看一下workLoopSync,workLoopConcurrent。

react-reconciler/src/ReactFiberWorkLoop.js
function workLoopSync() {
  while (workInProgress !== null) {
    workInProgress = performUnitOfWork(workInProgress);
  }
}
function workLoopConcurrent() {
  while (workInProgress !== null && !shouldYield()) {
    workInProgress = performUnitOfWork(workInProgress);
  }
}

在一次更新调度过程中,workLoop会更新每一个待更新的fiber。他们的区别在于异步模式会调用一个shouldYield() ,如果浏览器器没有空余时间,shouldYeild会终止循环,直到浏览器有空闲后再继续遍历,从而达到终止渲染的目的,这样就解决了一次行遍历大量的fiber,导致浏览器没有时间执行一些渲染任务,导致页面卡顿。

scheduleCallback

无论是上述正常更新任务 workLoopSync 还是低优先级的任务 workLoopConcurrent ,都是由调度器 scheduleCallback 统一调度的。sheduleCallback做了什么呢?

github.com/facebook/re…

function unstable_scheduleCallback(priorityLevel, callback, options) {
  var currentTime = getCurrentTime();    // 现在的时间

  var startTime;    // 开始时间
  if (typeof options === 'object' && options !== null) {
    var delay = options.delay;
    if (typeof delay === 'number' && delay > 0) {
      startTime = currentTime + delay;
    } else {
      startTime = currentTime;
    }
  } else {
    startTime = currentTime;
  }

  var timeout;
  switch (priorityLevel) {   // 调度任务的优先级
    case ImmediatePriority:
      timeout = IMMEDIATE_PRIORITY_TIMEOUT;
      break;
    case UserBlockingPriority:
      timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
      break;
    case IdlePriority:
      timeout = IDLE_PRIORITY_TIMEOUT;
      break;
    case LowPriority:
      timeout = LOW_PRIORITY_TIMEOUT;
      break;
    case NormalPriority:
    default:
      timeout = NORMAL_PRIORITY_TIMEOUT;
      break;
  }

  var expirationTime = startTime + timeout;  //超时时间
   // 创建一个任务 
  var newTask = {
    id: taskIdCounter++,
    callback,
    priorityLevel,
    startTime,
    expirationTime,
    sortIndex: -1,
  };
  if (enableProfiling) {
    newTask.isQueued = false;
  }
    // 开始时间大于现在时间
  if (startTime > currentTime) {
    // 通过开始时间排序
    newTask.sortIndex = startTime;
    push(timerQueue, newTask);      // 放入timeQueue
    // 当taskQueue队列没有任务  timerQueue中优先最高的任务是刚创建任务时
    if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
      // 是否有延时任务
      if (isHostTimeoutScheduled) {
        // cancelHostTimeout 用于清除requestHostTimeout 延时执行 handleTimeout。
        cancelHostTimeout();
      } else {
        isHostTimeoutScheduled = true;
      }
      // 执行setTimeout
      requestHostTimeout(handleTimeout, startTime - currentTime);
    }
  } else {
      // 通过 expirationTime 排序
    newTask.sortIndex = expirationTime;
    push(taskQueue, newTask);     // 放入taskQueue队列
    if (enableProfiling) {
      markTaskStart(newTask, currentTime);
      newTask.isQueued = true;
    }
   // 没有处于调度中的任务, 然后向浏览器请求一帧,浏览器空闲执行 flushWork
    if (!isHostCallbackScheduled && !isPerformingWork) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    }
  }

  return newTask;
}

看完上面代码你会了解到:

  • timeout 是根据调度优先级来生成,React 为了防止 requestIdleCallback 中的任务由于浏览器没有空闲时间而卡死,所以设置了 5 个优先级。
    • Immediate -1 需要立刻执行。
    • UserBlocking 250ms 超时时间250ms,一般指的是用户交互。
    • Normal 5000ms 超时时间5s,不需要直观立即变化的任务,比如网络请求。
    • Low 10000ms 超时时间10s,肯定要执行的任务,但是可以放在最后处理。
    • Idle 一些没有必要的任务,可能不会执行。
  • 会创建一个新的task,task会带着一些参数
  • 当 startTime > currentTime,意味着当前任务是被设置为 delay,task.sortIndex 被 startTime 赋值,并向 timerQueue push task,并依据任务的开始时间( startTime )排序
  • Else 的情况,也就是 当前任务没有设置 delay,task.sortIndex 被 expirationTime 赋值,并向 taskQueue push task,并依据任务的过期时间( expirationTime )
  • 在startTime < currentTime 会执行 requestHostCallback(flushWork),也就会申请时间切片,调度flushWork
  • 如果任务没有过期,用 requestHostTimeout 延时执行 handleTimeout。

上述代码看完你还会有下面疑惑🤔:

  • 调用requestIdleCallback,后续做了什么
  • flushWork起到了什么作用
  • requestHostTimeout、cancelHostTimeout、handleTimeout做了什么? -- 这个留到最后

performWorkUntilDeadline

回头看看时间分片,Scheduler调用requestIdleCallback申请时间切片时,flushWork作为参数传入并赋值给scheduledHostCallback,channel.port1这时候执行performWorkUntilDeadline,

接下来看一看performWorkUntilDeadline的实现

const performWorkUntilDeadline = () => {
  // scheduledHostCallback 来自于 requestHostCallback 中的 callback ,也就是flushWork
  if (scheduledHostCallback !== null) {
    const currentTime = getCurrentTime();
    // Yield after `yieldInterval` ms, regardless of where we are in the vsync
    // cycle. This means there's always time remaining at the beginning of
    // the message event.
    deadline = currentTime + yieldInterval;
    const hasTimeRemaining = true;

    // If a scheduler task throws, exit the current browser task so the
    // error can be observed.
    //
    // Intentionally not using a try-catch, since that makes some debugging
    // techniques harder. Instead, if `scheduledHostCallback` errors, then
    // `hasMoreWork` will remain true, and we'll continue the work loop.
    let hasMoreWork = true;
    try {
      // 执行flushWork
      hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
    } finally {
      if (hasMoreWork) {
        // If there's more work, schedule the next message event at the end
        // of the preceding one.
        port.postMessage(null);
      } else {
        isMessageLoopRunning = false;
        scheduledHostCallback = null;
      }
    }
  } else {
    isMessageLoopRunning = false;
  }
  // Yielding to the browser will give it a chance to paint, so we can
  // reset this.
  needsPaint = false;
};
  • yieldInterval 被定义为 5ms,代表了调用的最小间隔
  • scheduledHostCallback 来自于 requestHostCallback 中的 callback,也就是flushWork
  • 调用 scheduledHostCallback ,并返回当前是否有更多的任务需要执行。如果有将会递归调用 performWorkUntilDeadline

flushWork

function flushWork(hasTimeRemaining, initialTime) {
  if (enableProfiling) {
    markSchedulerUnsuspended(initialTime);
  }

  // We'll need a host callback the next time work is scheduled.
  isHostCallbackScheduled = false;
  // 如果有延时任务,那么先暂定延时任务
  if (isHostTimeoutScheduled) {
    // We scheduled a timeout but it's no longer needed. Cancel it.
    isHostTimeoutScheduled = false;
    cancelHostTimeout();
  }

  isPerformingWork = true;
  const previousPriorityLevel = currentPriorityLevel;
  try {
    if (enableProfiling) {
      try {
        return workLoop(hasTimeRemaining, initialTime);
      } catch (error) {
        if (currentTask !== null) {
          const currentTime = getCurrentTime();
          markTaskErrored(currentTask, currentTime);
          currentTask.isQueued = false;
        }
        throw error;
      }
    } else {
      // No catch in prod code path.
      return workLoop(hasTimeRemaining, initialTime);
    }
  } finally {
    currentTask = null;
    currentPriorityLevel = previousPriorityLevel;
    isPerformingWork = false;
    if (enableProfiling) {
      const currentTime = getCurrentTime();
      markSchedulerSuspended(currentTime);
    }
  }
}
  • 重置了 isHostTimeoutScheduled 的状态,确保在 flush 执行时,可以让新的任务被 schedule
  • flushWork 如果有延时任务执行的话,那么会先暂停延时任务
  • flushWork 返回了 workLoop() 的结果,下面看看workLoop()

workLoop

function workLoop(hasTimeRemaining, initialTime) {
  let currentTime = initialTime;
  advanceTimers(currentTime);
  // 将taskQueue中第一个取出来
  currentTask = peek(taskQueue);
  while (
    currentTask !== null &&
    !(enableSchedulerDebugging && isSchedulerPaused)
  ) {
    if (
      currentTask.expirationTime > currentTime &&
      (!hasTimeRemaining || shouldYieldToHost())
    ) {
      // This currentTask hasn't expired, and we've reached the deadline.
      break;
    }
    const callback = currentTask.callback;
    if (typeof callback === 'function') {
      currentTask.callback = null;
      currentPriorityLevel = currentTask.priorityLevel;
      const didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
      markTaskRun(currentTask, currentTime);
      const continuationCallback = callback(didUserCallbackTimeout);
      currentTime = getCurrentTime();
      if (typeof continuationCallback === 'function') {
        currentTask.callback = continuationCallback;
        markTaskYield(currentTask, currentTime);
      } else {
        if (enableProfiling) {
          markTaskCompleted(currentTask, currentTime);
          currentTask.isQueued = false;
        }
        if (currentTask === peek(taskQueue)) {
          pop(taskQueue);
        }
      }
      advanceTimers(currentTime);
    } else {
      pop(taskQueue);
    }
    currentTask = peek(taskQueue);
  }
  // Return whether there's additional work
  if (currentTask !== null) {
     // 这里返回的true会返回给performWorkUntilDeadline中hasMoreWork,然后再次申请时间片
    return true;
  } else {
    const firstTimer = peek(timerQueue);
    if (firstTimer !== null) {
      requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
    }
    return false;
  }
}
  • 整个方法中,有很多次调用 advanceTimers,让我们稍后看一下实现

  • currentTask = peek(taskQueue),peek taskQueue 中优先级最高的任务(不会从 Queue 移除 task)

  • 执行 Loop,如果 currentTask 存在

  • 检查当前任务未过期的情况下 是否 当前有剩余时间 或者 需要让出给高优先级的任务

    • 我们等下再来看 shouldYieldToHost
  • 执行 currentTask.callback,并将当前任务是否过期作为参数。这个 callback 会根据当前是否过期状态,缓存当前执行结果,返回未来可能会继续执行的方法:continuationCallback

    • 是不是记起来了? Fiber 可中断继续机制
    • callback 返回也可能为 非函数,代表任务可能已经完成,将从 taskQueue 中 pop 掉该任务
    • currentTask.callback 可以看到要符合 continuationCallback 的运作过程,所以这个函数是要满足一些设计才可以在 Scheduler 正常工作的
  • 最后将从 taskQueue 中再 peek 一个任务出来,继续执行 loop

    • 还记得刚才的 continuationCallback 吗,如果上一个任务缓存了结果,那么并不会在后面 pop
    • 所以这里 peak 出来的任务,还是上一个被中断的任务

advanceTimers

function advanceTimers(currentTime) {
  // Check for tasks that are no longer delayed and add them to the queue.
  let timer = peek(timerQueue);
  while (timer !== null) {
    if (timer.callback === null) {
      // Timer was cancelled.
      pop(timerQueue);
    } else if (timer.startTime <= currentTime) {
      // Timer fired. Transfer to the task queue.
      pop(timerQueue);
      timer.sortIndex = timer.expirationTime;
      push(taskQueue, timer);
      if (enableProfiling) {
        markTaskStart(timer, currentTime);
        timer.isQueued = true;
      }
    } else {
      // Remaining timers are pending.
      return;
    }
    timer = peek(timerQueue);
  }
}
  • advanceTimers 的作用是将 timerTask 中已经到了执行时间的 task,push 到 taskQueue,

shouldYield 中止 workloop

function shouldYieldToHost() {
  if (
    enableIsInputPending &&
    navigator !== undefined &&
    navigator.scheduling !== undefined &&
    navigator.scheduling.isInputPending !== undefined
  ) {
    const scheduling = navigator.scheduling;
    const currentTime = getCurrentTime();
    if (currentTime >= deadline) {
      // There's no time left. We may want to yield control of the main
      // thread, so the browser can perform high priority tasks. The main ones
      // are painting and user input. If there's a pending paint or a pending
      // input, then we should yield. But if there's neither, then we can
      // yield less often while remaining responsive. We'll eventually yield
      // regardless, since there could be a pending paint that wasn't
      // accompanied by a call to `requestPaint`, or other main thread tasks
      // like network events.
      if (needsPaint || scheduling.isInputPending()) {
        // There is either a pending paint or a pending input.
        return true;
      }
      // There's no pending input. Only yield if we've reached the max
      // yield interval.
      return currentTime >= maxYieldInterval;
    } else {
      // There's still time left in the frame.
      return false;
    }
  } else {
    // `isInputPending` is not available. Since we have no way of knowing if
    // there's pending input, always yield at the end of the frame.
    return getCurrentTime() >= deadline;
  }
}
  • 首先进行了 navigator.scheduling 这个 API 的宿主环境检测

    • Update 11-19-2020: 在 Chrome 87 上已经可以使用该 API
    • navigator.scheduling.isInputPending() 用来判断当前是否有用户的输入操作
  • 如果当前时间不够了,将控制权还给主线程,去满足优先执行 Painting 和 User Input,

  • 当然就算没有高优先级操作,最后还是会保证在一定的阈值让给主线程:maxYieldInterval

  • isInputPending 不可用的情况下,直接计算任务,已经超时了返回true直接停止任务。

requestHostTimeout 、cancelHostTimeout

到此其实调度基本讲完毕,但还有异步调度流程,也就是在Scheduler中,当startTime > currentTime时候执行的是requestHostTimeout而不是requestIdleCallback,下面就看看requestHostTimeout将handleTimeout作为参数做了什么?

function requestHostTimeout(callback, ms) {
  taskTimeoutID = setTimeout(() => {
    callback(getCurrentTime());
  }, ms);
}
function cancelHostTimeout() {
  clearTimeout(taskTimeoutID);
  taskTimeoutID = -1;
}

当有一个任务没有超时,React 把它放入 timerQueue中了,但是它什么时候执行呢 ?这个时候 Schedule 用 requestHostTimeout 让一个未过期的任务能够到达恰好过期的状态, 那么需要延迟 startTime - currentTime 毫秒就可以了。requestHostTimeout 就是通过 setTimeout 来进行延时指定时间的。而cancelHostTimeout就是用来清空这个延时器。

handleTimeout

延时指定时间后,调用的 handleTimeout 函数, handleTimeout 会把任务重新放在 requestHostCallback 调度。

function handleTimeout(currentTime) {
  isHostTimeoutScheduled = false;
  advanceTimers(currentTime);
    
  if (!isHostCallbackScheduled) {
    if (peek(taskQueue) !== null) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    } else {
      const firstTimer = peek(timerQueue);
      if (firstTimer !== null) {
        requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
      }
    }
  }
}
  • 开启advanceTimers,将 timeQueue 中过期的任务转移到 taskQueue 中
  • 没有处于调度中,判断有没有过期任务,没有的话调用requestHostCallback请求时间切片, 否则开启reaquestHostTimeout执行延时器。

至此调度和时间片完毕

小结

Scheduler大致运作原理

  • scheduleCallback 开始执行任务,确立新任务在 Scheduler 的优先级以及排序索引和 Callback 等属性,并依据是否 delay 将任务按照 sortIndex 放入两个 Queue 中
  • requestHostCallback 利用 MessageChannel 发送消息,在浏览器渲染后(也就是下一帧的开始)调用 performWorkUntilDeadline,并设置 deadline,执行 scheduledHostCallback 也就是 flushWork
  • 在 flushWork 开始了 workLoop,不断去按照优先级执行 taskQueue 对应的任务,并且在执行前会检查当前时间是否超过 deadline,超过会让出主线程以执行高优先级任务。在执行期间会利用 advanceTimers 进行 taskQueue 和 timerQueue 的实时整理,task 的处理函数支持中断缓存结果,并返回 continuationCallback,未来继续执行

image.png

Scheduler中断、恢复、判断

  • 判断:workLoop是在performWorkUntilDeadline函数里执行,这个函数调用是在这一帧有剩余时间时执行,workLoop会在执行时检查 当前任务未过期的情况下 是否 当前有剩余时间 或者 需要让出给高优先级的任务(shouldYieldToHost),shouldYieldToHost判断现在时间有没有超过到期时间。
  • 恢复:是在performWorkUntilDeadline拿到workLoop返回值为true继续调用port.postMessage(null) 让他下一帧时继续执行过期任务队列的第一个 也就是上一帧没执行完的任务,continuationCallback里面缓存的就是上次未执行完的函数
  • 中断:是在workLoop中,shouldYieldToHost为ture时就会中断workLoop中while会执行break,那么这时候workInProgress就会不为空,那么就代表打断。

参考博客: