flushWork

flushWork is a wrapper around workLoop. It prepares Scheduler's global state before work starts and restores that state afterward.

function flushWork(initialTime: number) {
  isHostCallbackScheduled = false;
  if (isHostTimeoutScheduled) {
    isHostTimeoutScheduled = false;
    cancelHostTimeout();
  }

  isPerformingWork = true;
  const previousPriorityLevel = currentPriorityLevel;
  try {
    return workLoop(initialTime);
  } finally {
    currentTask = null;
    currentPriorityLevel = previousPriorityLevel;
    isPerformingWork = false;
  }
}

Resetting Host Callback State

The first line clears isHostCallbackScheduled:

isHostCallbackScheduled = false;

The scheduled host callback has now started running, so Scheduler can allow a future host callback to be scheduled if more work is added later.

Cancelling an Unneeded Host Timeout

Next, Scheduler cancels a pending host timeout if one exists:

if (isHostTimeoutScheduled) {
  isHostTimeoutScheduled = false;
  cancelHostTimeout();
}

Host timeouts are used to wake Scheduler when delayed tasks become ready. But if flushWork is already running, workLoop will call advanceTimers and check timerQueue itself. The pending timeout may no longer be necessary.

Protecting Against Re-entrance

Before calling workLoop, Scheduler marks that work is currently being performed:

isPerformingWork = true;

scheduleCallback checks this flag before requesting another host callback:

if (!isHostCallbackScheduled && !isPerformingWork) {
  isHostCallbackScheduled = true;
  requestHostCallback();
}

If new work is scheduled while Scheduler is already inside workLoop, Scheduler avoids posting a duplicate host callback immediately. The existing loop or the next scheduled slice will pick it up.

Restoring Priority State

workLoop changes currentPriorityLevel while it executes each task. flushWork saves the previous priority and restores it in finally:

const previousPriorityLevel = currentPriorityLevel;
try {
  return workLoop(initialTime);
} finally {
  currentTask = null;
  currentPriorityLevel = previousPriorityLevel;
  isPerformingWork = false;
}

This cleanup runs whether workLoop completes normally, yields, or throws. Without it, global Scheduler state could leak from one task into unrelated work.

Summary

flushWork does not decide which task runs. That is workLoop's job. flushWork makes the environment around workLoop consistent: scheduling flags are reset, timer callbacks are cancelled when redundant, re-entrance is tracked, and global state is restored afterward.