How to Build a Dynamic Typewriter Effect for AI Search with Vue
This article walks through the evolution of a typewriter‑style text animation for AI‑driven search results, from a simple pure‑text implementation using setInterval to a sophisticated Vue component that handles markdown, embedded cards, escape characters, variable typing speed, and DOM diffing to deliver a smooth, interactive user experience.
Introduction
In modern front‑end development, the typewriter effect is a creative interaction that displays text character‑by‑character, providing users with a unique visual experience. It is especially suitable for AI search scenarios where large language models stream output incrementally.
Why Use a Typewriter Effect in AI Search
Alleviate waiting anxiety – incremental rendering gives users real‑time feedback, reducing perceived latency.
Simulate natural dialogue – the paced reveal mimics human typing, enhancing immersion.
Improve information intake – breaking up dense text eases visual and cognitive load.
Highlight AI‑generated content – users recognize the output as live AI results rather than a static answer.
Early Implementation (Pure Text)
The initial solution simply concatenated streamed markdown into a buffer and used setInterval to update the displayed substring via innerHTML:
let fullText = 'test text'; // full HTML text
let index = 0; // current character index
let timer = window.setInterval(() => {
++index;
$dom.innerHTML = fullText.substring(0, index);
}, 40);Choosing innerHTML over appendChild avoided the complexity of handling incomplete markdown fragments returned by the server.
Challenges as Requirements Grew
Later product iterations required embedding rich cards (apps, stocks, videos) within the typed text, demanding a more flexible and performant approach than the naïve innerHTML method.
Modern Framework Implementation (Vue)
Using Vue’s virtual DOM, a singleton pattern ensures that elements are reused rather than recreated, preserving state and improving performance. The component parses streamed markdown, converts it to HTML with ultrahtml, and renders the resulting DOM tree recursively.
private init() {
let fileList = require.context('@/components/common/box', true, /\.vue$/);
fileList.keys().forEach((filePath) => {
let startIndex = filePath.lastIndexOf('/') + 1;
let endIndex = filePath.lastIndexOf('.');
let tagName = filePath.substring(startIndex, endIndex);
this.widgetMap[tagName] = fileList(filePath).default;
});
}HTML conversion includes a debounce to avoid jitter when responses arrive quickly:
let toRenderHtml = this.rawHtml.substring(0, this.curIndex);
let dom = {
type: ELEMENT_NODE,
name: 'p',
children: parse(toRenderHtml).children
};The recursive render component handles text nodes, custom widget tags, and raw HTML tags:
render(h) {
// omitted for brevity
if (this.dom.type === TEXT_NODE) {
return this.renderTextNode({ h, element: this.dom });
}
let tagName = this.dom.type === ELEMENT_NODE ? this.dom.name : 'div';
if (this.$factory.hasTag(tagName)) {
let widget = this.$factory.getWidget(tagName);
return h(widget, { props: { ... } }, []);
}
return h(tagName, { attrs: { ...this.dom.attributes } }, renderChildren);
}Handling Edge Cases
HTML tags inside the stream – when the current character is '<', the parser jumps to the matching '>' to avoid character‑by‑character display of tags.
Escape characters – similar logic groups '&' sequences until the full escape entity is consumed.
Variable typing speed – speed is adjusted based on remaining characters using a configurable strategy.
Re‑rendering after HTML changes – detect HTML changes, then advance the index until the rendered text length exceeds the previous snapshot, using textContent for comparison.
Conclusion
By leveraging Vue’s reactive system and a well‑structured component architecture, the typewriter effect becomes performant, extensible, and capable of mixing rich card widgets with streamed text, delivering a polished AI‑search experience.
Future Outlook
The techniques described lay a foundation for further innovations as AI and front‑end ecosystems evolve, encouraging developers to experiment with new interaction patterns and optimizations.
vivo Internet Technology
Sharing practical vivo Internet technology insights and salon events, plus the latest industry news and hot conferences.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
