Courses / Frontend System Design, with JavaScript Foundations / Chapter 4
Module 2 · JavaScript Foundations · Chapter 4 of 21
Promises, Async Code and the Browser Event Loop
Builds on Values, Coercion, Scope and Closures. Next up: TypeScript for Frontend Engineers.
Part 1 · From callbacks to promises
Callbacks and their limits
Browsers and servers wait on slow things: files, networks, timers. Code that waits needs a way to say "continue when this is done" without freezing everything else.
The oldest answer is the callback: you pass a function, and the runtime calls it later. Node settled on the error-first form, where the callback receives an error or null as its first argument. Callbacks work, but three problems appear as soon as steps depend on each other. Nesting grows to the right with every step. Error handling must be repeated at each level, because a throw inside a later callback cannot be caught by a try around the call that registered it. And you hand control to the other side: it may call your function twice, or never.
A promise is an object that stands for a value that is not ready yet. It fixes those three problems by giving you something you can pass around, chain and attach one error handler to. Node offers both styles for files, so the same failure can be compared in each.
import { readFile } from 'node:fs' function readCb(path, cb) { readFile(path, 'utf8', (err, text) => cb(err, text)) } readCb('missing.txt', (err, text) => { console.log(err ? err.code : 'ok') }) import { readFile as readP } from 'node:fs/promises' try { await readP('missing.txt', 'utf8') } catch (e) { console.log(e.code, e.syscall) }
A missing file, callback style and promise style
ENOENT ENOENT open
Output (Node 24)
Both styles report the same Node error code, ENOENT, which means the file does not exist. You can wrap any callback API in a promise yourself. The new Promise constructor gives you two functions, resolve and reject, and you call one of them from inside the callback.
function getPrice(id, cb) { setTimeout(() => { if (id === 0) cb(new Error('unknown id')) else cb(null, id * 100) }, 5) } const getPriceAsync = (id) => new Promise((resolve, reject) => { getPrice(id, (err, value) => (err ? reject(err) : resolve(value))) }) console.log(await getPriceAsync(7)) await getPriceAsync(0).catch((e) => console.log('failed:', e.message))
Wrapping an error-first callback API
700
failed: unknown idOutput (Node 24)
The three states of a promise
A promise is in one of three states. Pending means no result yet. Fulfilled means it finished with a value. Rejected means it failed with a reason, usually an Error. Fulfilled and rejected together are called settled. A settled promise never changes again.
const pending = new Promise(() => {}) const ok = Promise.resolve(42) const bad = Promise.reject(new Error('no stock')) console.log(pending, ok) console.log(await bad.catch((e) => 'rejected with ' + e.message)) const once = new Promise((resolve, reject) => { resolve('first') resolve('second') reject(new Error('too late')) }) console.log(await once) const p = Promise.resolve(1) const q = p.then((n) => n + 1) console.log(p === q, q instanceof Promise) console.log(await q)
States, settling once, and then returning a new promise
Promise { <pending> } Promise { 42 }
rejected with no stock
first
false true
2Output (Node 24)
The first line prints a pending promise and a fulfilled one holding 42. The second shows a rejected promise turned into text with catch. The once promise called resolve twice and then reject, and only the first call counted, so it fulfilled with "first". That guarantee is why a promise is safe to hand to code you do not control.
The last lines show that .then always returns a new promise. p === q is false, and q resolved to 2, the return value of the callback. That is what makes chains possible.
Chaining and error propagation
Each .then receives the result of the step before and returns the input for the next. If the callback returns a plain value, the next step gets it. If it returns another promise, the chain waits for that promise and passes on its result. If it throws, the returned promise rejects, and the rejection skips every .then until a .catch.
const wait = (ms, v) => new Promise((r) => setTimeout(r, ms, v)) wait(10, 'cart') .then((v) => { console.log('1', v) return wait(10, 'payment') }) .then((v) => { console.log('2', v) return 'plain value' }) .then((v) => { console.log('3', v) throw new Error('card declined') }) .then(() => console.log('skipped')) .catch((e) => { console.log('caught:', e.message) return 'recovered' }) .then((v) => console.log('after catch:', v)) .finally(() => console.log('finally runs'))
A chain with a failure in the middle
1 cart 2 payment 3 plain value caught: card declined after catch: recovered finally runs
Output (Node 24)
Steps 1 to 3 ran in order, and each waited for the promise before it. After the third step threw, the then that prints skipped never ran. The catch handled the error and returned "recovered", which fulfilled the chain again, so the next then ran. finally runs either way and does not change the value.
One bug appears constantly. A step that starts asynchronous work but does not return it breaks the chain, because the next step receives undefined right away.
const wait = (ms, v) => new Promise((r) => setTimeout(r, ms, v)) const r = await wait(5, 'a') .then((v) => { wait(5, 'inner') }) .then((v) => v) console.log('forgot return:', r) const r2 = await wait(5, 'a') .then((v) => wait(5, 'inner')) .then((v) => v) console.log('with return:', r2)
Forgetting a return
forgot return: undefined with return: inner
Output (Node 24)
A promise calls resolve("a") and then resolve("b"). What does it hold?
"a". A promise settles once, and later calls are ignored.
A .then callback throws. What happens to the rest of the chain?
Part 2 · async and await
Waiting inside a function
An async function always returns a promise: the value it returns fulfils it, and an exception it throws rejects it. Inside, the await operator pauses that function until a promise settles, then continues with the value, or throws the rejection reason.
Only the one function is paused. The rest of the program keeps running, because await hands control back to the event loop, which is covered in the lessons that follow. The code reads as a straight line, but a promise still sits underneath.
The most common mistake is awaiting steps one after another when they do not depend on each other. Three independent lookups of 100 ms each take 300 ms in sequence, and about 100 ms when started together.
const wait = (ms, v) => new Promise((r) => setTimeout(r, ms, v)) const price = () => wait(100, 499) const stock = () => wait(100, 12) const rating = () => wait(100, 4.5) async function sequential() { const a = await price() const b = await stock() const c = await rating() return [a, b, c] } async function parallel() { const [a, b, c] = await Promise.all([price(), stock(), rating()]) return [a, b, c] } async function timed(name, fn) { const t0 = performance.now() const result = await fn() const ms = Math.round(performance.now() - t0) console.log(name.padEnd(10), JSON.stringify(result), ms + ' ms') } await timed('sequential', sequential) await timed('parallel', parallel)
The same three lookups, sequential and parallel
sequential [499,12,4.5] 321 ms parallel [499,12,4.5] 107 ms
Output (Node 24; timings vary on each run)
The Promise.all version starts all three before waiting, so the delays overlap. The numbers are from one run on this machine, and they vary. The ratio is the point: roughly three times. Await sequentially only when a step needs the result of the one before.
Loops and await
Arrays of work meet await often. A for...of loop with await inside runs the steps one after another, so total time adds up. Promise.all over a map starts every step at once. The third style, forEach with an async callback, looks similar but is a trap: forEach ignores the promises the callback returns, so the code after the loop runs before any step has finished.
const wait = (ms) => new Promise((r) => setTimeout(r, ms)) const ids = [1, 2, 3] const fetchOne = async (id) => { await wait(20); return id * 10 } let t = performance.now() const a = [] for (const id of ids) a.push(await fetchOne(id)) console.log('for...of ', a, Math.round(performance.now() - t) + ' ms') t = performance.now() const b = await Promise.all(ids.map(fetchOne)) console.log('map + all ', b, Math.round(performance.now() - t) + ' ms') const c = [] ids.forEach(async (id) => c.push(await fetchOne(id))) console.log('forEach ', c, 'right after the loop') await wait(50) console.log('forEach ', c, 'later')
Three ways to loop over async work
for...of [ 10, 20, 30 ] 94 ms map + all [ 10, 20, 30 ] 28 ms forEach [] right after the loop forEach [ 10, 20, 30 ] later
Output (Node 24; timings vary on each run)
After the forEach loop the result array was still empty, and it filled up later. Use for...of when order or one-at-a-time matters, Promise.all with map when steps are independent, and never forEach with await. If hundreds of steps would overload a server, a limit on how many run at once is the next step, and the machine coding chapter builds one.
Errors with try, catch and finally
With await, a rejected promise becomes a thrown exception at the await line, so ordinary try, catch and finally work. One detail trips people. Returning a promise from inside a try without await hands it to the caller, so the catch in the function never sees its failure.
const fail = (ms) => new Promise((_, rej) => setTimeout(rej, ms, new Error('boom ' + ms))) async function load() { try { await fail(5) console.log('not reached') } catch (e) { console.log('caught', e.message) return 'fallback' } finally { console.log('cleanup') } } console.log(await load()) async function returnsPromise() { return 1 } console.log(returnsPromise() instanceof Promise)
try, catch and finally
caught boom 5
cleanup
fallback
trueOutput (Node 24)
const fail = (ms) => new Promise((_, rej) => setTimeout(rej, ms, new Error('boom ' + ms))) async function forgetAwait() { try { return fail(5) } catch (e) { return 'caught inside' } } try { await forgetAwait() } catch (e) { console.log('escaped the try:', e.message) } async function withAwait() { try { return await fail(5) } catch (e) { return 'caught inside' } } console.log(await withAwait())
return versus return await inside a try
escaped the try: boom 5
caught insideOutput (Node 24)
load caught the error, ran cleanup in finally and returned "fallback". returnsPromise() is a Promise even though it returns a number. The second file prints the last two lines. In forgetAwait, the failure escaped the try, and the caller printed it. In withAwait, the await kept the failure inside, so caught inside was returned. Write return await inside a try when you want the local catch to handle it.
Rejections nobody handles
A rejected promise with no handler is an unhandled rejection. In Node, since version 15, this ends the process with an error by default. Browsers do not stop; they report it to the console and fire an unhandledrejection event on the window. The script below launches a child Node process with one such promise and a 10 ms timer, and reports what happened.
import { spawnSync } from 'node:child_process' const r = spawnSync('node', ['l2-unhandled2.mjs'], { encoding: 'utf8' }) console.log('exit code:', r.status) console.log('stdout:', JSON.stringify(r.stdout)) const first = r.stderr.split('\n').find((l) => l.startsWith('Error')) console.log('stderr:', first)
Run the failing script in a child process
exit code: 1 stdout: "" stderr: Error: nobody listens
Output (Node 24)
The child exited with code 1, printed nothing on stdout, and the timer never fired, because the process was already gone. The first line on stderr names the error. In a server, an unhandled rejection can mean a crashed process, and in a browser it usually means a request that failed silently. Attach a .catch or use try and catch, and use a top-level handler only to log what slipped through.
How long do three independent 100 ms awaits take in sequence, and with Promise.all?
- About 300 ms in sequence and about 100 ms with
Promise.all. In the run above: 321 ms and 107 ms.
When does return await promise differ from return promise inside a try?
- With
await, a rejection is thrown inside the function, so itscatchruns. Without it, the promise goes to the caller and thecatchnever sees the failure.
What does Node do with an unhandled rejection by default?
- It ends the process with an error and exit code 1, as the child run showed.
Part 3 · Combinators and cancellation
Working with many promises
Four static methods combine promises, and they differ in when they settle and what they return.
| Method | Fulfils when | Rejects when | Result |
|---|---|---|---|
Promise.all | Every input fulfils | Any input rejects (first one wins) | Array of values, in input order |
Promise.allSettled | Every input settles | Never | Array of { status, value | reason } |
Promise.race | The first input settles with a value | The first input settles with a rejection | That one result |
Promise.any | The first input fulfils | Every input rejects | That value, or an AggregateError |
Promise.allFulfils whenEvery input fulfils
Rejects whenAny input rejects (first one wins)
ResultArray of values, in input order
Promise.allSettledFulfils whenEvery input settles
Reading the results
all returns values in input order, not completion order, and fails as soon as one input fails, with that error. The other promises keep running; only the result is lost. Use allSettled when you want every outcome, for example a dashboard where one widget failing must not hide the rest.
race returns whatever settles first, even a rejection. any ignores rejections until all inputs have failed, and then rejects with an AggregateError that lists every reason in its errors array. In the run, its message is All promises were rejected.
The last three lines are edge cases. Promise.all([]) is already fulfilled with an empty array, as the printed Promise { [] } shows. Promise.race([]) stays pending forever. Promise.any([]) rejects at once with an AggregateError, because there is no value to wait for. Empty input is common when a filtered list has no items, so know these three.
A timeout for any promise
Promise.race gives a simple way to put a time limit on a promise: race it against a promise that rejects after a delay. Clear the timer when the race ends so it does not keep the process alive.
const wait = (ms, v) => new Promise((r) => setTimeout(r, ms, v)) function withTimeout(promise, ms) { let timer const limit = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('timed out')), ms) }) return Promise.race([promise, limit]) .finally(() => clearTimeout(timer)) } const slowJob = async () => { await wait(100) console.log('slow job finished anyway') return 'done' } try { await withTimeout(slowJob(), 20) } catch (e) { console.log('caller sees:', e.message) } console.log(await withTimeout(wait(5, 'fast'), 50)) await wait(150)
A withTimeout helper and what it cannot do
caller sees: timed out fast slow job finished anyway
Output (Node 24)
The caller got timed out after 20 ms, but the slow job was not stopped: it printed slow job finished anyway later. Racing only changes what the caller waits for. To stop the work itself, the operation must accept an abort signal, which is the next topic.
Cancelling work
A promise cannot be cancelled. What you can do is tell the underlying operation to stop, and the standard tool is the AbortController. You create one, pass its signal to an API that accepts a signal, such as fetch, and call abort() when the result is no longer wanted. The API then rejects with a reason. AbortSignal.timeout(ms) makes a signal that aborts itself after a delay.
import { createServer } from 'node:http' const server = createServer((req, res) => { setTimeout(() => res.end('late reply'), 300) }) await new Promise((r) => server.listen(55801, '127.0.0.1', r)) const url = 'http://127.0.0.1:55801/slow' const show = (label, e) => console.log(label, e.name, '|', e.message) try { await fetch(url, { signal: AbortSignal.timeout(50) }) } catch (e) { show('timeout:', e) } const ctl = new AbortController() setTimeout(() => ctl.abort(), 50) try { await fetch(url, { signal: ctl.signal }) } catch (e) { show('abort():', e) } const ctl2 = new AbortController() setTimeout(() => ctl2.abort(new Error('user left')), 50) try { await fetch(url, { signal: ctl2.signal }) } catch (e) { show('with reason:', e) } const early = AbortSignal.abort() console.log(early.aborted, early.reason.name) server.close() server.closeAllConnections()
Timeouts and aborts against a slow local server
timeout: TimeoutError | The operation was aborted due to timeout abort(): AbortError | This operation was aborted with reason: Error | user left true AbortError
Output (Node 24)
The timeout signal rejected with a TimeoutError, and a manual abort() gave an AbortError. When abort was given a reason, the rejection carried that reason instead. The wording of the message differs between runtimes: Node printed This operation was aborted, and Chrome printed signal is aborted without reason for a plain abort() in the stream-reader run of the first chapter. Test the error name, not the text. An already aborted signal makes fetch reject immediately.
Abort is how you stop stale requests, such as the earlier search when the user types again, and how you free a connection when a user leaves a page. It is also supported by addEventListener, which the DOM chapter covers.
Which combinator returns the first successful value and ignores earlier failures?
Part 4 · Tasks and microtasks in the browser
One thread, two kinds of queued work
A page's JavaScript runs on one main thread, and the event loop decides what runs next. The work comes in two kinds. A task is a unit of work such as running a script, a timer callback or an event listener. A microtask is a short follow-up, such as a promise reaction or a function passed to queueMicrotask.
The rule is simple. The loop takes one task, runs it to the end, and then runs a microtask checkpoint: every queued microtask runs, including ones added while the checkpoint is running, before anything else. Only then can the loop pick another task or render. The HTML standard says the choice of which task queue to take from is made "in an implementation-defined manner", so the order of tasks from different sources is not guaranteed.
import { withPage } from './chrome.mjs' const log = await withPage((page) => page.evaluate(async () => { const out = [] setTimeout(() => out.push('timeout 0'), 0) Promise.resolve().then(() => out.push('promise then')) queueMicrotask(() => out.push('queueMicrotask')) new MutationObserver(() => out.push('mutation observer')) .observe(document.body, { childList: true }) document.body.append('x') out.push('sync end') await new Promise((r) => setTimeout(r, 20)) return out })) console.log(log.join('\n'))
Five ways to schedule work, run in Chrome 157
sync end
promise then
queueMicrotask
mutation observer
timeout 0Output (Chrome 157)
sync end comes first because the script is still running. The promise callback, the queueMicrotask callback and the MutationObserver callback are all microtasks, so they run in the order they were queued, as soon as the script ends. The timer callback is a task, so it waits for the next turn of the loop even though its delay is 0.
Reading the order
The scene walks through six lines that add an animation frame callback to the mix. The same lines, with console.log replaced by a log array, were run in Chrome 157 five times, and every run logged sync start, sync end, promise, microtask, timeout, frame.
Watch for microtasks running before the next task, and rAF waiting for a frame
Read it as steps
Microtasks run when the script ends; the timer is a task of its own.
The timer ran before the frame in this run, but the standard does not fix that order: a frame is produced when the browser decides it is time to draw, not at a set number of timer turns. What is fixed is the relation between a task and the microtasks it queued: they run first.
Microtasks run to completion
A microtask that queues another microtask does not let the loop go. The nested one runs in the same checkpoint. The same applies to a promise callback that schedules more promise callbacks.
import { withPage } from './chrome.mjs' const log = await withPage((page) => page.evaluate(async () => { const out = [] setTimeout(() => { out.push('T1') Promise.resolve().then(() => out.push('T1 micro')) }, 0) setTimeout(() => out.push('T2'), 0) Promise.resolve().then(() => { out.push('M1') queueMicrotask(() => out.push('M1 child')) }) Promise.resolve().then(() => out.push('M2')) out.push('S') await new Promise((r) => setTimeout(r, 20)) return out })) console.log(log.join(' '))
Nested microtasks and two timers
S M1 M2 M1 child T1 T1 micro T2
Output (Chrome 157)
Read the line from left to right. S is the script. Then M1, M2 and M1 child: the child microtask, queued while M1 ran, ran before the loop moved on. Only after the checkpoint did the first timer task run (T1), and its own microtask T1 micro ran before the second timer T2. Every task is followed by its own checkpoint.
The same rule has a sharp edge. A microtask that keeps scheduling itself starves the loop: no task, no rendering, no input can run.
import { withPage } from './chrome.mjs' const log = await withPage((page) => page.evaluate(async () => { const out = [] let n = 0 setTimeout(() => { out.push('timeout ran after ' + n + ' microtasks') }, 0) function loop() { if (++n < 100000) queueMicrotask(loop) } loop() await new Promise((r) => setTimeout(r, 50)) return out })) console.log(log.join('\n'))
A microtask loop holds back a timer
timeout ran after 100000 microtasksOutput (Chrome 157)
The timer was set before the loop began, yet it ran only after all 1,00,000 microtasks. A bounded loop like this is harmless; an unbounded one freezes the page.
In what order do setTimeout(f, 0), Promise.resolve().then(g) and the end of the current script run?
- The current script finishes, then the promise callback
g(a microtask), thenf(a task), as the Chrome run showed.
Part 5 · Rendering in the loop
Where the frame fits
The browser draws the page at rendering opportunities, which usually follow the display's refresh rate. Between tasks, if an opportunity has come, the loop runs an "update the rendering" step. The HTML standard describes it as a global task on a rendering task source. In it, the browser runs the page's animation frame callbacks (the functions given to requestAnimationFrame), then recalculates styles and layout and paints.
This is why requestAnimationFrame is the right place to change visuals: the callback runs just before the frame is produced, so the change appears in that frame. A callback that registers another one gets it run in the next frame, not the same one. A setTimeout callback runs whenever its task comes up, which may be before or after the next frame, and so it is the wrong tool for animation.
import { withPage } from './chrome.mjs' const log = await withPage((page) => page.evaluate(async () => { const out = [] const el = document.body setTimeout(() => out.push('timeout 0'), 0) requestAnimationFrame(() => { out.push('rAF 1') Promise.resolve().then(() => out.push('microtask in rAF 1')) requestAnimationFrame(() => out.push('rAF 2 (next frame)')) setTimeout(() => out.push('timeout from rAF 1'), 0) }) Promise.resolve().then(() => out.push('microtask')) out.push('sync end') await new Promise((r) => setTimeout(r, 500)) return out })) console.log(log.join('\n'))
Timers, microtasks and frames in one script
sync end microtask timeout 0 rAF 1 microtask in rAF 1 timeout from rAF 1 rAF 2 (next frame)
Output (Chrome 157, one run; the timer position can vary)
The first frame callback ran after the script, the first timer and the microtask. A microtask queued inside the callback ran straight after it, and the callback it registered ran in the next frame. Whether the timer queued from inside the first frame callback runs before or after the next frame is left to the browser; here it came first.
A real click and a scripted click
The microtask checkpoint happens whenever the JavaScript stack becomes empty after a callback. Two ways of triggering a click show this. When a person clicks, the browser calls each listener from native code with an empty stack, so a checkpoint runs after each listener. When a script calls el.click(), the script is still on the stack while the listeners run, so the checkpoint waits until the script ends.
import { withPage } from './chrome.mjs' const html = '<!doctype html><button id="b">go</button>' await withPage(async (page) => { await page.evaluate(() => { window.out = [] const b = document.getElementById('b') b.addEventListener('click', () => { out.push('L1') Promise.resolve().then(() => out.push('M1')) }) b.addEventListener('click', () => { out.push('L2') Promise.resolve().then(() => out.push('M2')) }) }) await page.click('#b') const real = await page.evaluate(() => out.splice(0)) console.log('real click:', real.join(' ')) await page.evaluate(() => document.getElementById('b').click()) const scripted = await page.evaluate(() => out.splice(0)) console.log('el.click(): ', scripted.join(' ')) }, html)
One button, two listeners, two kinds of click
real click: L1 M1 L2 M2 el.click(): L1 L2 M1 M2
Output (Chrome 157)
Watch for the stack emptying between listeners on a real click
Read it as steps
Where the stack empties decides where microtasks run.
What runs where
Putting the pieces together gives one picture of a turn of the loop.
| Step | What runs | Examples |
|---|---|---|
| 1. A task | One unit of work, to the end | A script, a timer callback, an input event listener |
| 2. Microtask checkpoint | All microtasks, until the queue is empty | Promise reactions, queueMicrotask, MutationObserver |
| 3. Rendering opportunity? | If one is due: animation frame callbacks, then style, layout, paint | requestAnimationFrame callbacks, ResizeObserver callbacks |
| 4. Next turn | The loop picks another task | Any queued task, in the browser's chosen order |
Two practical rules follow. Do visual updates in requestAnimationFrame so they land in the next frame. And keep every task short, because the page cannot render or respond until the current task and its microtasks finish. The next lesson measures what happens when a task is not short.
Why do timers make poor animation drivers compared with requestAnimationFrame?
- A timer runs when its task comes up, unrelated to when the next frame is drawn. The frame callback runs just before the frame, so its change appears in that frame.
A user clicks a button with two listeners that each queue a promise callback. In what order do they run?
L1 M1 L2 M2. After each listener the stack is empty, so its microtasks run before the next listener.
Part 6 · Long tasks and yielding
Why a long task hurts
Because a task runs to completion, a task that takes 300 ms leaves the page unable to draw a frame or answer a tap for 300 ms. The platform names the problem: a long task is any task that runs for more than 50 milliseconds, and the part beyond 50 ms is its blocking period. Responsiveness metrics, such as Interaction to Next Paint, include the time an input waits behind such tasks.
The fix is to split the work and yield to the main thread between pieces, so the loop can render and handle input in the gaps. The scene contrasts a blocked task and a chunked one.
Watch for the frame that cannot run until the long task ends
Read it as steps
A frame waits for a long task to end; chunked work lets frames through.
In the first half, nothing could be drawn until the 300 ms task ended. In the second, each slice finished quickly and gave the loop control back, so a waiting frame or input event could run between slices. The total work is the same; the difference is when the loop gets control back. The scene is a model: the measurements at the end of this lesson show that whether a frame actually runs after every slice depends on how you yield.
Yielding in code
scheduler.yield() returns a promise that resolves after the browser has had a chance to handle other work, such as input. Per web.dev, your function then continues before other tasks of similar priority are started, so a queued timer or third-party task cannot jump ahead of it. Per MDN's compatibility data it is available in Chrome and Edge 129 and Firefox 142, and not in Safari, so check for it and fall back to a promise resolved by setTimeout(0). The code below does that.
const work = (n) => { let s = 0 for (let i = 0; i < n; i++) s += Math.sqrt(i) return s } const yieldNow = () => 'scheduler' in self && scheduler.yield ? scheduler.yield() : new Promise((r) => setTimeout(r, 0))
Yield helper and the two chunking styles
const t0 = performance.now() if (mode === 'block') { work(total) } else if (mode === 'chunked') { for (let done = 0; done < total; done += chunk) { work(chunk) await yieldNow() } } else { let last = performance.now() for (let done = 0; done < total; done += chunk / 20) { work(chunk / 20) if (performance.now() - last > 10) { await yieldNow() last = performance.now() } } }
Block, fixed chunks, or time-based slices
Fixed-size chunks yield after a set amount of work. The time-based version does a small piece of work, checks the clock, and yields only when 10 ms have passed since the last yield. The harness around these lines runs each mode in Chrome, listens for long tasks with a PerformanceObserver, and records the longest gap between animation frames. Its full source is in the lab folder.
Measuring the three modes
The numbers below are lab numbers from one run on this machine, in Chrome 157 with a Playwright-driven headless browser. They vary on every run, and headless frame pacing is not what a user's display does. Read the long-task columns as the main result, and the frame-gap column as a comparison between rows. The second block throttles the CPU four times with the DevTools protocol.
CPU throttling 1x (all times in ms) mode | work ms | long tasks | longest | frame gap block | 292 | 1 | 292 | 283 chunked | 313 | 0 | 0 | 117 timed | 296 | 0 | 0 | 108 CPU throttling 4x (all times in ms) mode | work ms | long tasks | longest | frame gap block | 1360 | 1 | 1360 | 1350 chunked | 1427 | 16 | 89 | 183 timed | 1402 | 0 | 0 | 117
Output (Chrome 157, lab, this machine)
Unthrottled, the blocked task is one long task of about 292 ms, and the frame gap is about as long. Both chunked modes produced no long task. With a 4x slowdown, the blocked task grew to 1,360 ms. The fixed chunks, sized for the fast run at about 20 ms of work, now took longer than 50 ms each, and the run recorded 16 long tasks with the longest at 89 ms. Only the time-based slices stayed clean, with no long task.
Two ways to yield
The frame-gap column holds a second result. With scheduler.yield, the chunked rows still went more than 100 ms without a frame. To compare, the same harness was run again with the setTimeout fallback forced.
CPU throttling 1x (all times in ms) mode | work ms | long tasks | longest | frame gap block | 283 | 1 | 283 | 275 chunked | 362 | 0 | 0 | 25 timed | 396 | 0 | 0 | 9 CPU throttling 4x (all times in ms) mode | work ms | long tasks | longest | frame gap block | 1305 | 1 | 1305 | 1292 chunked | 1516 | 16 | 95 | 92 timed | 2227 | 0 | 0 | 17
Output (Chrome 157, lab, this machine, setTimeout yield)
With setTimeout, frames came through between slices: the longest gap in the time-based rows fell to 9 ms unthrottled and 17 ms at 4x. The price was total time: the time-based slices took 396 ms against 296 ms for the same work unthrottled, and 2,227 ms against 1,402 ms at 4x. With either way of yielding, the time-based slices produced no long task, which is what lets input in; the fixed chunks at 4x had 16 long tasks either way. In this lab, then, scheduler.yield finished the work sooner but left longer frame gaps than setTimeout; the cause is not established. These are one headless run each, and real displays pace frames differently, so measure your own page before choosing.
So size slices by time, not by item count. Many phones are slower than the machine you develop on, which is what CPU throttling imitates, so a chunk that is safe here may not be safe there. One more caution: per web.dev, isInputPending is no longer recommended as a way to decide when to yield; yield regularly instead.
| Term | Meaning |
|---|---|
| Task | A unit of work the event loop runs to completion |
| Microtask | A short follow-up run in the checkpoint after a task |
| Long task | A task that runs longer than 50 ms |