FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Typewriter Effects vs. DOM Flushing

Compare paced character reveals with frame-batched AI stream updates to balance visible freshness, render work, reading cadence, and accessible announcements.

Freshness: current•12 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

Mental model

Typewriter effects and frame-batched flushing control how streamed model text reaches the screen. A typewriter deliberately reveals buffered characters at a chosen rate; a frame-batched renderer groups chunks and commits available text at display cadence. Both can look active, but the former adds reading delay and neither changes model time to first token. Measure visible freshness, drain time, and announcement load.

Learning outcomes

  • Separate model time to first output, stream arrival, DOM commit, and visible paint.
  • Calculate the backlog a paced reveal creates when text arrives faster than it is shown.
  • Choose a rendering cadence and screen-reader announcement strategy for a streaming interface.

Theory

A streaming response passes through several clocks. The model produces output; a server encodes it into a stream; a browser decodes incoming bytes into text; application state accumulates deltas; a framework may commit an updated DOM; the browser later performs style, layout, and paint work. A network chunk is not necessarily one model token, one word, or one visual update. If the UI reports “first token” when it means “first text node,” the metric combines different work and obscures which layer is slow.

Use separate timestamps for the request, first output received, first DOM commit, and first visible content. The last two are not interchangeable: an element can exist in the DOM before the browser has painted it. A requestAnimationFrame callback is scheduled around a rendering opportunity, which makes it useful for coalescing updates, but the callback itself is not proof that a user saw pixels. For performance work, distinguish server or SDK time-to-first-output from client time-to-first-visible-text, then inspect browser traces when paint timing matters.

The Vercel AI SDK exposes streamed text as a ReadableStream and an async iterable, so transport consumption and UI presentation can be scheduled independently. A frame-batched renderer reads the deltas, appends them to a pending buffer, and allows at most one requestAnimationFrame callback to commit that buffer. A callback that runs at 60 Hz gives about 16.7 milliseconds between opportunities; if ten chunks arrive during that interval, one state update can include all ten. This avoids reconciling the message tree once for every small network event, while keeping newly received text close to the display cadence.

A typewriter effect inserts another queue. Let r_in be the arrival rate in characters per second, r_reveal the rate at which the interface exposes buffered characters, and T the time the stream is active in seconds. Under constant rates, the backlog at stream completion is:

Bend=max⁡(0,(rin−rreveal)T),Tdrain=BendrrevealB_{\text{end}}=\max(0,(r_{\text{in}}-r_{\text{reveal}})T),\qquad T_{\text{drain}}=\frac{B_{\text{end}}}{r_{\text{reveal}}}

Here B_end is measured in characters and T_drain in seconds; the drain formula applies when r_reveal is greater than zero. If 360 characters arrive uniformly over 2 seconds, r_in is 180 characters per second. A typewriter revealing 60 characters per second displays 120 while data is arriving, leaves 240 buffered, and needs another 4 seconds after network completion to show everything. The model and transport finished after 2 seconds, but the last character becomes visible 4 seconds later. This calculation ignores tokenization and scheduling jitter; measure actual arrivals and rendered text in a real trace.

A frame-batched renderer makes a different trade-off. If those 360 characters arrive in 360 small chunks over the same 2 seconds, a 60 Hz foreground tab has roughly 120 frame opportunities. One pending callback per frame can reduce about 360 update calls to approximately 120 commits, while the visible output still catches up at the next available rendering opportunity. A busy main thread or a display refresh rate below 60 Hz reduces that count and increases freshness delay. The point is not to force 60 updates each second; it is to avoid coupling every arbitrary transport boundary to a separate DOM commit.

Keep the buffer keyed to one response and preserve stream order. At completion, flush any remaining text immediately so an animation queue cannot hold the final sentence hostage. On cancellation, decide whether to discard pending text or retain the partial response. Background tabs may throttle or pause animation frames, so cap buffered memory and flush or resume deliberately when visibility returns. If text includes Markdown, code, or structured output, do not reveal a half-interpreted construct as though it were final. Character schedulers also need grapheme-aware boundaries: JavaScript string indices can split emoji or combining sequences, so a “character” may be more than one code unit.

The Human-AI Interaction guidelines emphasize timing services in context and helping people understand what an AI system can do. An artificial typing delay can be appropriate for a short, scripted demonstration or a user-selected reading cadence; it should not masquerade as model latency or be the only way to receive the answer. For generated code, JSON, commands, or safety decisions, prefer immediate availability or a clearly provisional preview because delayed characters can make copying, verification, and correction harder.

Accessibility adds a second cadence. A live region that changes on every token may be announced repeatedly and make the response difficult to follow. WCAG 2.2 distinguishes programmatically available status messages from ordinary content changes and includes requirements for certain automatically updating content. Provide a concise “response in progress” status, expose the completed message, and announce meaningful sentence or completion boundaries rather than every character. Test with assistive technology and offer a way to stop a long reveal or show the text immediately when a paced presentation is part of the product.

Decode ordered response deltas
Accumulate pending text per response
Commit the buffer at a rendering opportunity
Flush or cancel pending text explicitly
Announce status at a usable cadence
Conceptual teaching model synthesized from:vercel-ai-sdk-stream,vercel-ai-sdk-ui-stream-protocol,mdn-window-requestanimationframe,human-ai-guidelines,w3c-wcag22

Trade-offs

Flushing each decoded delta gives the shortest delay from arrival to DOM, but can make framework reconciliation and layout work track network chunk size. Providers and intermediaries choose chunks for transport efficiency, not for visual rhythm; one provider may send a word, another several token pieces, and another a partial UTF-8 sequence that the decoder must finish. A frame buffer creates a small scheduling delay, usually bounded by the next foreground rendering opportunity, in exchange for fewer commits. Under heavy computation, that bound can expand, so collect p50 and p95 arrival-to-commit delay instead of assuming a fixed frame cost.

A typewriter effect can make a short answer feel paced and can give users a moment to follow a demonstration. The same effect makes the interface reveal text slower than the system generated it, accumulates memory when r_in exceeds r_reveal, and can leave the end of a long answer hidden after generation is complete. Provide a visible skip or show-all control, persist a user preference if the product relies on that mode, and keep the actual response available to copying and search. Do not infer that users prefer slower output from the fact that animation looks active.

Measure more than render count. Track request-to-first-output, request-to-first-visible-text, arrival-to-commit delay, pending characters at completion, post-completion drain time, cancellation rate, and long main-thread tasks. For screen-reader users, also test whether progress and completion messages arrive at a usable pace. Compare the same model, stream, device class, and response length; otherwise a faster first render can simply reflect a shorter answer or a different network path.

Failure modes and misconceptions

  • Calling a DOM commit a paint. State updates can produce a DOM change before pixels are presented. Label the measurements precisely and use browser performance traces for paint analysis.
  • Treating transport chunks as tokens or words. Chunk boundaries are transport artifacts. Decode text incrementally and avoid revealing broken Unicode sequences or unstable Markdown.
  • Using one animation rate for every response. A rate that is readable for a two-line explanation can create a multi-second tail for a long answer. Flush on completion or let the user skip.
  • Letting a typewriter queue grow without a bound. If incoming text outpaces reveal, memory and completion delay grow. Stop pacing, show the remainder, or cancel with an explicit partial-response state when the queue limit is reached.
  • Scheduling one DOM commit per delta. Small frequent updates can consume the main thread and worsen layout or input responsiveness. Coalesce by frame, then profile actual devices.
  • Announcing every token in a live region. Assistive technology may repeat each mutation and drown out the response. Separate progress status from message content and announce useful milestones.
  • Assuming requestAnimationFrame always runs on time. Background tabs and long tasks may throttle callbacks. Handle visibility changes and flush the final buffer through a path that does not depend on a future frame.

Decision scenario

A coding assistant streams a 700-character patch description and a code block. The network finishes in 3 seconds, but the interface reveals characters at 45 per second. A screen-reader test also reports a new live-region announcement for each token. The team should remove the paced reveal for code, batch received text at the display cadence, and flush the remaining buffer as soon as the response completes. Keep one concise progress status separate from the message, and let the user reveal the complete text immediately.

Before releasing the change, replay a fixed stream with timestamps at the same 360-character rate used in the worked example. Compare request-to-first-visible-text, arrival-to-commit p95, commits per response, backlog at completion, and user input responsiveness on a foreground and background tab. Then verify completion and cancellation behavior with keyboard navigation and a screen reader. If the target metric improves while text freshness, copy access, or status announcements get worse, tune the buffer policy instead of masking the difference with a longer typewriter animation.

Implementation pattern

This scheduler groups decoded deltas into one append per rendering opportunity. It does not force synchronous framework work and does not claim that the callback itself proves the pixels were presented. The completion path cancels the pending frame and commits its remainder immediately.

typescript
type FrameFlusher = {
push: (chunk: string) => void;
finish: () => void;
cancel: () => void;
};
​
export function createFrameFlusher(commit: (text: string) => void): FrameFlusher {
let pending = "";
let frame: number | undefined;
let closed = false;
​
const flushFrame = () => {
frame = undefined;
if (closed || pending.length === 0) return;
const text = pending;
pending = "";
commit(text);
};
​
return {
push(chunk) {
if (closed || chunk.length === 0) return;
pending += chunk;
if (frame === undefined) frame = requestAnimationFrame(flushFrame);
},
finish() {
if (closed) return;
if (frame !== undefined) cancelAnimationFrame(frame);
frame = undefined;
closed = true;
const remainder = pending;
pending = "";
if (remainder) commit(remainder);
},
cancel() {
if (closed) return;
closed = true;
if (frame !== undefined) cancelAnimationFrame(frame);
frame = undefined;
pending = "";
},
};
}
​
const chunks = ["Frame batching ", "keeps text fresh."];
const updates: string[] = [];
const output = createFrameFlusher((text) => updates.push(text));
for (const chunk of chunks) output.push(chunk);
output.finish();
console.assert(updates.join("") === "Frame batching keeps text fresh.");
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next