如何为带项目符号的打字机效果代码添加启动、循环及项目间延迟?
打字机效果代码改造方案
核心修正点
- 移除原代码中阻塞CPU的空循环
sleep函数,这类写法会冻结整个页面交互,完全不适合做延迟调度 - 所有延迟统一用非阻塞的
setTimeout实现,全覆盖三个需求场景的时间配置 - 拆分原整段多行文本为独立的项目符号条目,给每个条目单独配置打字间隔,替换原全局统一300ms延迟的逻辑
- 修正原代码中
<pre>标签的语法错误(原标签缺少闭合尖括号)
改造后可直接运行代码
<!DOCTYPE html> <html> <body> <pre id="typing"></pre> <script> // 全局可配置时间参数,直接修改数字即可调整延迟 const CONFIG = { startDelay: 3000, // 打字机正式启动前的等待延迟(单位:毫秒) loopRestDelay: 2000, // 一整轮内容打完、进入下一轮循环前的等待延迟 lineSwitchDelay: 500, // 单个项目符号内容打完、切换到下一个项目符号前的间隔 }; // 每个项目符号的独立打字速度配置,可单独调整 const bulletConfig = [ { content: '• I m Mr. Frits.', charInterval: 150 }, { content: '• and I love Pakistan...:)', charInterval: 300 } ]; // 全局状态变量 let currentBulletIndex = 0; // 当前正在输出第几个项目符号 let currentCharIndex = 0; // 当前已经输出到单个项目符号的第几个字符 let fullTypedString = ''; // 已输出的全部文本缓存 // 打字核心逻辑 function type() { const currentBullet = bulletConfig[currentBulletIndex]; const currentChar = currentBullet.content[currentCharIndex]; fullTypedString += currentChar; document.getElementById('typing').innerHTML = fullTypedString.fontsize(6); document.getElementById('typing').style.fontFamily = "monospace"; document.getElementById("typing").style.color = "black"; document.getElementById("typing").style.fontWeight = "normal"; currentCharIndex++; let nextDelay = currentBullet.charInterval; // 判断当前单个项目符号是否输出完成 if (currentCharIndex === currentBullet.content.length) { currentBulletIndex++; currentCharIndex = 0; fullTypedString += '\n'; nextDelay = CONFIG.lineSwitchDelay; // 判断是否所有项目符号都输出完成(一整轮结束) if (currentBulletIndex === bulletConfig.length) { fullTypedString = ''; // 清空文本准备下一轮循环 currentBulletIndex = 0; nextDelay = CONFIG.loopRestDelay; } } setTimeout(type, nextDelay); } // 启动逻辑:先等待配置的启动延迟,再触发打字效果 setTimeout(type, CONFIG.startDelay); </script> </body> </html>
参数调整说明
- 修改
CONFIG.startDelay的数值,可调整页面加载完成后,等待多久开始第一波打字 - 修改
CONFIG.loopRestDelay的数值,可调整一整段循环播完、重新从头输出前的等待时间 - 修改
bulletConfig中每个条目的charInterval数值,可给每个项目符号单独设置打字速度,数字越小打字越快,数字越大打字越慢 - 修改
CONFIG.lineSwitchDelay的数值,可调整两个相邻项目符号之间的切换间隔
内容的提问来源于stack exchange,提问作者Shehryar
相关产品推荐
相关产品推荐

