The Scheduler
Relevant source files
The following files were used as context for generating this wiki page:
- packages/scheduler/src/Scheduler.js
- packages/scheduler/src/SchedulerMinHeap.js
- packages/scheduler/src/SchedulerPriorities.js
- packages/react-reconciler/src/ReactFiberRootScheduler.js
- packages/scheduler/src/tests/Scheduler-test.js
- packages/scheduler/src/tests/SchedulerMock-test.js
- packages/scheduler/src/tests/SchedulerPostTask-test.js
- packages/scheduler/src/forks/SchedulerNative.js
- packages/scheduler/src/tests/SchedulerProfiling-test.js
The scheduler package provides a cooperative scheduler for browser and other JavaScript environments. It is a core component used internally by React to manage and prioritize work, such as rendering updates, in a way that doesn't block the main thread. This allows for features like time-slicing and concurrent rendering, ensuring a responsive user interface even during heavy workloads.
The scheduler's main purpose is to execute callbacks based on priority and to yield back to the main thread periodically to prevent dropped frames. It uses different underlying mechanisms depending on the environment, such as MessageChannel or postTask in browsers and setImmediate in Node.js.
Core Concepts
Priorities
The scheduler defines several priority levels to manage the order of task execution. Higher priority tasks are executed before lower priority tasks. Each priority level corresponds to a specific timeout value, after which a task is considered "expired" and must be executed synchronously.
| Priority Level | Timeout (ms) | Description |
|---|---|---|
ImmediatePriority | -1 | Executed synchronously. Must not be interrupted. |
UserBlockingPriority | 250 | For user-initiated tasks that should feel immediate (e.g., button clicks). |
NormalPriority | 5000 | The default priority for most tasks. |
LowPriority | 10000 | For background tasks that can be deferred. |
IdlePriority | No timeout | For tasks that should only run when the system is idle. These tasks never expire. |
Sources: packages/scheduler/src/SchedulerPriorities.js, packages/scheduler/src/tests/SchedulerMock-test.js:100-104
Task Object
A task is a unit of work scheduled with the scheduler. It is represented by an object with the following properties:
| Property | Type | Description |
|---|---|---|
id | number | A unique, incrementing ID for the task. |
callback | function | The function to be executed. Can be null if the task is canceled. |
priorityLevel | number | The priority of the task, corresponding to the levels above. |
startTime | number | The time the task was scheduled. For delayed tasks, this is the time it should start. |
expirationTime | number | The time at which the task expires and must be run. |
sortIndex | number | Used as a tie-breaker for tasks with the same expiration time. Initially set to startTime. |
Sources: packages/scheduler/src/Scheduler.js:81-88
Time Slicing and Yielding
To prevent blocking the main thread, the scheduler performs work in small chunks. After each chunk, it checks if it should yield control back to the browser. The unstable_shouldYield() function determines this by checking if the deadline has been exceeded. The deadline is typically 5ms but can be configured. If a task's callback returns another function, that function is treated as a continuation and is scheduled to run in a subsequent macrotask, even if time remains in the current frame.
Sources: packages/scheduler/src/Scheduler.js:389-391, packages/scheduler/src/tests/Scheduler-test.js:203-221
Task Management and Prioritization
The scheduler uses two min-heaps to manage tasks:
taskQueue: Stores tasks that are ready to be executed.timerQueue: Stores tasks that are scheduled with a delay.
Tasks in the heaps are ordered by their expirationTime, and for tasks with the same expiration, by their startTime.
Sources: packages/scheduler/src/Scheduler.js:69-70, packages/scheduler/src/SchedulerMinHeap.js
This diagram illustrates the flow of a task through the scheduler's queues.
Min-Heap Implementation
The SchedulerMinHeap.js file provides a min-heap implementation used for the taskQueue and timerQueue. It ensures that the task with the lowest sortIndex (earliest expiration time) is always at the top of the heap, allowing for O(1) access to the next task and O(log n) for insertions and deletions.
Key functions include:
push(heap, node): Adds a node to the heap.pop(heap): Removes and returns the minimum node from the heap.peek(heap): Returns the minimum node without removing it.
Sources: packages/scheduler/src/SchedulerMinHeap.js
Scheduler API
The scheduler exposes an unstable API for scheduling and managing callbacks.
| Function | Description |
|---|---|
unstable_scheduleCallback(priority, callback, options) | Schedules a callback to be executed. options can include a delay. Returns a task object. |
unstable_cancelCallback(task) | Cancels a previously scheduled task. |
unstable_getCurrentPriorityLevel() | Returns the priority level of the currently executing task. |
unstable_shouldYield() | Returns true if the scheduler should yield to the main thread. |
unstable_now() | Returns the current high-resolution time. |
unstable_requestPaint() | A hint to the scheduler that a paint is coming. This can cause shouldYield to return true. |
unstable_runWithPriority(priority, callback) | Runs a function with a specific priority level. |
unstable_wrapCallback(callback) | Wraps a callback so that it inherits the priority of the context in which it is created. |
Sources: packages/scheduler/src/Scheduler.js, packages/scheduler/src/tests/SchedulerMock-test.js
Execution and Work Loop
The core of the scheduler is the workLoop, which is responsible for executing tasks from the taskQueue.
Scheduling a Macrotask
When a task is scheduled and the queue is not empty, requestHostCallback is called. This function uses an available mechanism in the host environment to schedule a macrotask that will execute the workLoop. The preferred order of mechanisms is:
scheduler.postTask(if available)MessageChannelsetImmediate(for Node.js)setTimeout(as a fallback)
Sources: packages/scheduler/src/Scheduler.js:456-484, packages/scheduler/src/tests/SchedulerPostTask-test.js, packages/scheduler/src/tests/SchedulerSetImmediate-test.js
The workLoop
The workLoop function runs as long as there are tasks in the queue and the deadline has not been exceeded (!shouldYield()). In each iteration, it:
- Retrieves the highest-priority task from the
taskQueueusingpeek(). - If the task has expired, it executes it synchronously.
- If the task has not expired, it checks
shouldYield(). If it should not yield, it executes the task. - If the task callback returns a function (a "continuation"), that function becomes the new callback for the current task, and the scheduler yields, scheduling a new macrotask to continue the work later.
- If a task throws an error, the scheduler catches it, reports it, and moves on to the next task, ensuring one failed task doesn't halt all work.
The following sequence diagram shows the process of scheduling and executing a task with a continuation.
Environment-Specific Implementations
The scheduler adapts its macrotask scheduling mechanism based on the available browser or JS environment APIs.
postTask: In modern browsers supportingscheduler.postTask, priorities are mapped directly to browser-level priorities (user-blocking,user-visible,background), allowing the browser to manage task execution more intelligently.
Sources: packages/scheduler/src/tests/SchedulerPostTask-test.js:203-225MessageChannel: This is the primary mechanism in most browsers. It creates a macrotask that executes with a clean stack, which is faster and more reliable thansetTimeout(0).
Sources: packages/scheduler/src/Scheduler.js:472-484, packages/scheduler/src/tests/Scheduler-test.js:90-101setImmediate: In Node.js environments whereMessageChannelis not available,setImmediateis used.
Sources: packages/scheduler/src/Scheduler.js:466-470, packages/scheduler/src/tests/SchedulerSetImmediate-test.jssetTimeout: This is the universal fallback if no other mechanism is available.
Sources: packages/scheduler/src/Scheduler.js:486-490, packages/scheduler/src/tests/SchedulerSetTimeout-test.js- Native Scheduler: In environments like React Native, the scheduler can delegate its functions to a native implementation provided by the
nativeRuntimeSchedulerglobal object.
Sources: packages/scheduler/src/forks/SchedulerNative.js:28-66
Integration with React Reconciler
The React reconciler uses the scheduler to manage updates. The ReactFiberRootScheduler.js file acts as the bridge.
- When an update is scheduled on a Fiber root (e.g., via
setStateorroot.render), the reconciler determines the appropriate priority and usesensureRootIsScheduledto create a task. ensureRootIsScheduledcallsunstable_scheduleCallbackwith the correct priority, passingperformConcurrentWorkOnRootorperformSyncWorkOnRootas the callback.- This integrates React's rendering work into the scheduler's cooperative multitasking system, allowing renders to be prioritized, interrupted, and resumed.
Sources: packages/react-reconciler/src/ReactFiberRootScheduler.js:96-121
Profiling
The scheduler includes a profiling build that logs detailed events about its internal operations. When enabled, it can record:
TaskStartEventTaskCompleteEventTaskErrorEventTaskCancelEventTaskRunEventTaskYieldEventSchedulerSuspendEventSchedulerResumeEvent
This data can be used to generate flamegraphs and other visualizations to debug performance issues related to scheduling.
Sources: packages/scheduler/src/tests/SchedulerProfiling-test.js:80-97
Conclusion
The React Scheduler is a sophisticated system for managing units of work in a way that prevents blocking the main thread and keeps UIs responsive. By using priority levels, time-slicing, and environment-specific scheduling primitives, it provides the fundamental infrastructure for React's concurrent features. Its ability to handle task continuations, errors, and prioritization makes it a robust foundation for building fluid user experiences.