首页 > 解决方案 > 如何在一秒间隔内获取字符

问题描述

var firstChar = "S";
var secondChar = "O";
var thirdChar = "N";
var fourthChar = "Y";

setTimeout(function() {
  document.getElementById("charOne").innerHTML += firstChar;
}, 1000);
setTimeout(function() {
  document.getElementById("charTwo").innerHTML += secondChar;
}, 2000);
setTimeout(function() {
  document.getElementById("charThree").innerHTML += thirdChar;
}, 3000);
setTimeout(function() {
  document.getElementById("charFour").innerHTML += fourthChar;
}, 4000);
<span id="charOne"></span>
<span id="charTwo"></span>
<span id="charThree"></span>
<span id="charFour"></span>

上面的代码是由我完成的,但状态不佳我只想需要一个更灵活的脚本来帮助我在这里获得相同的结果,但具有更可靠的编码标准。或者我应该在其中使用 ARRAY 。

标签: javascripthtml

解决方案


我会改用单个字符串,并异步迭代它,创建新<span>的并将它们插入到文档中,而不是分配给现有的跨度:

const delay = ms => new Promise(res => setTimeout(res, ms));
(async () => {
  for (const char of 'SONY') {
    await delay(1000);
    document.body.insertAdjacentHTML('beforeend', ` <span>${char}</span>`);
  }
})();


推荐阅读