Split heavy work in React with scheduler.yield
If you run a heavy task in a plain loop, the input field shows no characters until the loop finishes, and the page freezes. When you put await scheduler.yield() inside the loop, the browser can handle input and painting first, then your code resumes.
However, in React, if the loop only calls setState, the progress display did not change until the work finished. To show progress, I call flushSync only once every 50 milliseconds. I also show how to add cancellation.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and a 4-core CPU. I used react and react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, then built for production with esbuild. The browser was Chromium 153 driven by Playwright. I ran it headless, and also measured some cases with a display under Xvfb. I did not test Firefox, Safari, real phones, or slow CPUs. Times are measured by when requestAnimationFrame (rAF below) is called, not when the screen is actually painted.
- 1. Without splitting, no input appears for 1.7 seconds
- 2. Waiting on scheduler.yield() inside the loop
- 3. With only setState, the progress count stays at "1" until the end
- 4. Painting before yielding with flushSync
- 5. The finished version that splits every 50 milliseconds
- 6. Cancel button and restarting mid-run
- 7. Differences from splitting with setTimeout
Without splitting, no input appears for 1.7 seconds
For the test, I used a component that runs 300 items in a row, each taking about 6 milliseconds. Pressing the "start" button starts the loop, and the counter (processed 0 / 300, labeled in Japanese in the UI) counts up. Below it is an input field, and the typed text is echoed after an "input:" label (the label is in Japanese in the UI).
When the loop was not split, the whole run took about 1.7 seconds (median of 5 runs: 1,682 ms). During that time, rAF was never called, and the screen stayed frozen. Characters typed during the run took a median of 1,217 ms to appear on screen. All of them appeared right after the loop ended.
Waiting on scheduler.yield() inside the loop
scheduler.yield() gives control of the main thread back to the browser and runs the rest of your code later. When you await the returned Promise, the browser handles input and other work in the meantime, then your code resumes from the next line.
MDN's compatibility table lists support from Chrome 129 and Firefox 142, and no support in Safari. So for browsers without it, I wrote a helper that falls back to setTimeout. The MDN explanation of the Prioritized Task Scheduling API includes a similar example that falls back to setTimeout.
// yieldToMain.ts
export function yieldToMain(): Promise<void> {
if (typeof globalThis.scheduler?.yield === 'function') {
return globalThis.scheduler.yield();
}
return new Promise((resolve) => setTimeout(resolve, 0));
}
The DOM types in TypeScript 7.0.2 already include scheduler and yield(), so tsc passed without adding any type declarations myself. When I removed window.scheduler and ran it, the helper switched to the setTimeout path, and the processing still ran to completion.
Inside the loop, I waited on yieldToMain() after each item.
for (let i = 0; i < TOTAL; i++) {
heavyItem(i);
setDone(i + 1);
await yieldToMain();
}
With this, characters typed during the run appeared on screen with a median delay of 7 ms. The total time had a median of 1,730 ms, almost the same as without splitting.
With only setState, the progress count stays at "1" until the end
The input field responded now, but the "processed" count did not advance. I ran it three times without typing. Each time, the only value shown during processing was "1", and it jumped to "300" the moment the loop finished.

React's re-rendering is scheduled by the scheduler package that react-dom uses. This is a different package from the browser's scheduler object. In the browser, this package schedules tasks using MessageChannel. On the other hand, as MDN explains, the continuation from scheduler.yield() is placed in a queue with raised priority, so it runs before postTask() tasks of the same priority. The spec note also says that the continuation of a yield() at default priority is meant to be treated as more important than many other tasks.
In the test with no typing, rAF was called about every 0.1 seconds during processing, but the processed count stayed at "1" until the end.
When I typed characters during processing, all 5 runs showed only 4 distinct values for the count during processing (not counting 0 at the start or 300 at the end).
Painting before yielding with flushSync
Wrapping setState in flushSync makes React render immediately and update the DOM. If you then wait on yieldToMain(), the browser shows the updated DOM on screen.
for (let i = 0; i < TOTAL; i++) {
heavyItem(i);
flushSync(() => setDone(i + 1));
await yieldToMain();
}
With this version, 16 to 17 distinct counts were visible in order during processing, even without typing. However, react.dev says flushSync is rarely needed and can significantly hurt app performance. If you call it on every item, that means 300 synchronous renders for 300 items.
So I decided to choose the splitting interval by time, and call flushSync only at those split points. For the interval, I used 50 milliseconds, the threshold that the Long Tasks API spec defines as a "long task". However, the following code checks the elapsed time after each item, so the gap between splits runs a bit over 50 milliseconds (the extra is at most one item plus the time for flushSync).
The finished version that splits every 50 milliseconds
Here is the finished component. Once more than 50 milliseconds have passed, it renders the count with flushSync, then waits on yieldToMain().
// HeavyTask.tsx
import { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { heavyItem } from './work';
import { yieldToMain } from './yieldToMain';
const TOTAL = 300;
export function HeavyTask() {
const [done, setDone] = useState(0);
const [running, setRunning] = useState(false);
const [text, setText] = useState('');
const controllerRef = useRef<AbortController | null>(null);
async function start() {
controllerRef.current?.abort();
const controller = new AbortController();
controllerRef.current = controller;
setRunning(true);
setDone(0);
let lastYield = performance.now();
for (let i = 0; i < TOTAL; i++) {
heavyItem(i);
if (performance.now() - lastYield > 50) {
flushSync(() => setDone(i + 1));
await yieldToMain();
if (controller.signal.aborted) return;
lastYield = performance.now();
}
}
setDone(TOTAL);
setRunning(false);
}
function cancel() {
controllerRef.current?.abort();
setRunning(false);
}
return (
<div>
<button onClick={start}>処理を始める</button>
<button onClick={cancel} disabled={!running}>中止</button>
<progress value={done} max={TOTAL} />
<p id="progress">処理済み {done} / {TOTAL}</p>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder="ここに入力" />
<p id="echo">入力:{text}</p>
</div>
);
}
In 5 runs, it took 1,670 to 1,796 ms from pressing the button until "300 / 300" appeared. During processing, the count advanced about every 0.1 seconds. Characters typed during the run appeared on screen in 16 to 40 ms. That is longer than the 7 ms median with setState and yield per item, but much shorter than the over-1-second delay without splitting.
Cancel button and restarting mid-run
scheduler.yield() itself takes no argument to stop it. (If you call it inside postTask(), the task's abort signal applies.) So in the finished version, I hold an AbortController myself, and each time yieldToMain() returns, I check signal.aborted and exit the loop.
I pressed "Cancel" about 0.5 seconds after processing started. The count stopped at "96 / 300" and did not change even after waiting 2.5 seconds. I also confirmed that the cancel button is enabled during processing.
If you press "start" again during processing, it first aborts the previous AbortController, then starts a new loop. I pressed it again after the count reached 134. The count started counting from the beginning again (9, 29, 50, …) and ended at 300. The display never mixed in numbers from the earlier loop.
Differences from splitting with setTimeout
I compared the same 300-item task split with setTimeout(resolve, 0) per item instead of scheduler.yield(). The numbers are medians of 5 runs. The row for "flushSync every 50 ms then yield" is the same splitting method as the finished version, measured with a separate test component for comparison.
| Approach | Total time | Time from keypress until the character appears | Interval between rAF calls | Count during processing |
|---|---|---|---|---|
| No splitting | 1,682 ms | 1,217 ms | Not called during processing | Does not advance |
| Yield per item (setState only) | 1,730 ms | 7 ms | 102 ms | Barely advances |
| Yield every 50 ms with flushSync | 1,674 ms | 24 ms | 104 ms | Advances |
| setTimeout per item | 2,985 ms | 13 ms | 17 ms | Advances |
Splitting with setTimeout made the total time about 1.3 seconds longer. When I reproduced the case without scheduler.yield() in Chromium, using flushSync and waiting on yieldToMain() for each item, the total took 3,004 ms.
As a rule for repeatedly nested setTimeout calls, MDN's setTimeout explanation says that after five nested setTimeout calls, the browser enforces a minimum delay of 4 ms.
On the other hand, when splitting with scheduler.yield(), rAF was called only about once every 100 ms. With setTimeout splitting, it was about once every 17 ms. This difference was the same in headless mode and in Chromium with a display under Xvfb. The count during processing advances about every 0.1 seconds, which is enough to show progress. However, an animation driven by rAF advances only about once every 0.1 seconds during processing.





