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

如何循环执行函数?实现HTML页面文字逐词输入并重复的问题

实现逐词输入并循环重复的解决方案

你的代码有两个关键问题导致无法实现循环效果:

  • 那个while (x = 0)的写法完全错误:首先这是赋值操作(不是判断相等的x == 0),其次JavaScript是单线程语言,同步while循环会直接阻塞浏览器主线程,导致setTimeout的回调根本没机会执行。
  • 原typeWriter函数写完文本后没有重置状态、触发下一轮输入的逻辑,所以只能执行一次。

下面是修改后的完整代码,实现逐字符输入完成后清空内容、延迟片刻再重新开始循环的效果:

<!DOCTYPE html>
<html>
<body>
  <div id="demo"></div>

  <script>
    let i = 0;
    const txt = 'Welcome';
    const typeSpeed = 70; // 逐字符输入的间隔,单位ms
    const resetDelay = 1000; // 输入完成后等待多久开始下一轮,单位ms

    function typeWriter() {
      const demoElement = document.getElementById("demo");
      if (i < txt.length) {
        demoElement.innerHTML += txt.charAt(i);
        i++;
        setTimeout(typeWriter, typeSpeed);
      } else {
        // 输入完成后,延迟重置并启动下一轮
        setTimeout(() => {
          i = 0; // 重置字符索引
          demoElement.innerHTML = ''; // 清空显示内容
          typeWriter(); // 重新调用输入函数
        }, resetDelay);
      }
    }

    // 页面加载完成后启动输入效果
    window.onload = typeWriter;
  </script>
</body>
</html>

关键修改点说明:

  • 把变量i改成let(比var更安全,避免变量提升带来的意外问题),固定文本txt用const声明(因为内容不会变化)。
  • 在typeWriter的else分支(输入完成时),添加了延迟回调逻辑:重置字符索引、清空目标元素内容,然后再次调用typeWriter开启下一轮输入。
  • 移除了错误的while循环,改用异步的方式实现循环,不会阻塞浏览器正常运行。

如果想要实现逐词输入(不是逐字符)的循环效果,比如文本是多单词组成的句子,你可以把文本拆成单词数组,调整代码如下:

let wordIndex = 0;
const words = ['Hello', 'there,', 'welcome', 'to', 'the', 'demo'];
const typeSpeed = 300; // 逐词输入的间隔,单位ms
const resetDelay = 1500;

function typeWriter() {
  const demoElement = document.getElementById("demo");
  if (wordIndex < words.length) {
    // 逐词添加,单词间自动加空格
    demoElement.innerHTML += (wordIndex === 0 ? '' : ' ') + words[wordIndex];
    wordIndex++;
    setTimeout(typeWriter, typeSpeed);
  } else {
    setTimeout(() => {
      wordIndex = 0;
      demoElement.innerHTML = '';
      typeWriter();
    }, resetDelay);
  }
}

window.onload = typeWriter;

这样就能完美实现你想要的循环逐词/逐字符输入效果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 12:27:50