You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用定时器异步更新状态变量实现逐词渲染?

异步逐词渲染句子的问题及尝试方案

我尝试异步逐词渲染句子,例如将“A new hope”按1秒的间隔依次渲染“A”、“new”、“hope”,但试了几种方法都无法实现可靠渲染,存在间隔不一致或切换时文字闪烁的问题。

尝试的方法代码片段

方法0 - 使用setInterval

let curWordIdx = 0;
let intervalId = setInterval(() => updateText(wordList[curWordIdx++]), 1000);

useEffect(() => {
  return () => {
    clearInterval(intervalId);
  };
});

方法1 - 使用setTimeout

for (let index = 0; index < wordList.length; index++) {
  setTimeout(() => {
    updateText(wordList[index]);
  }, index * 1000);
}

方法2 - 使用RxJS

interval(1000).pipe(
  take(wordList.length),
  map(i => wordList[i])
).subscribe({
  next: (word) => updateText(word),
  error: _ => console.log('error'),
});

内容的提问来源于stack exchange,提问作者Krishnabm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:04:58