javascript - 如何在一秒间隔内获取字符
问题描述
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 。
解决方案
我会改用单个字符串,并异步迭代它,创建新<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>`);
}
})();
推荐阅读
- selenium - 为什么 WebDriverEventListener 不支持 iframe 事件?
- python - 遍历python中的JSON并根据键过滤值以获得所需的结果
- docker - Docker UCP API 修剪
- kotlin - 使用自定义(ConsumerAware)错误处理程序时如何寻求和提交?
- flutter - Flutter 无限滚动 - 滚动监听器触发器
- reactjs - 更新了 npm 依赖,现在它不会编译
- c++ - 无法将 DefineClass (JNI) 与 Qt 资源一起使用
- operating-system - 如何构建一个从 4000 多个嵌入式设备获取 GPS 数据并实时处理的系统
- php - 根据相同的键值连接值
- java - JBeret 和 JSR352,关于重启和持久数据的一些说明