SetTimeout让我感到困惑,我需要能够暂时解决它
我有两个独立的div元素,并且我有一个定义每个元素的函数,并且应该只作用于该元素。因此,当我调用typeField(name,element1)
时,它应该只键入element1
,类似地,然后我调用typeField(address,element2)
,它应该只键入element2
..但目前,如果你检查我的代码实现,它混合了字符,我不确定为什么。
所以我的两个问题是
- 我在代码中做错了什么,混淆了innerHTML元素中的内容?
- 解决后,如何使第一个元素成为类型,并在完成时启动下一个元素
如能帮助解决此问题,我们将不胜感激。
这是指向我的代码的链接
https://codepen.io/alimbolar/pen/Rwjoqbm?editors=1111
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">const typewriter1 = document.getElementById('typewriter1');
const typewriter2 = document.getElementById('typewriter2');
const name = 'Alim Bolar';
const address = "Some part of the world";
const currentLocation = "Bali, Indonesia";
const profile = "Frontend Development, Backend Development, WordPress Development"
let content = "";
let i = 0;
function typeField(x, element) {
if (i < x.length) {
alphabet = x.charAt(i);
content = content + alphabet;
element.innerHTML = content;
i++;
setTimeout(function() {
typeField(x, element)
}, 500);
}
}
typeField(name, typewriter1);
typeField(address, typewriter2);
<header>
<div>NAME : <span id="typewriter1"></span></div>
<div>ADDRESS : <span id="typewriter2"></span></div>
</header>
解决方案
您需要
- 不让
i
或content
是全局的,因为这样它将被typeField
的所有调用共享 - 将
typeField
分配给一个永久承诺,从而将进一步的调用链接到
考虑await
在循环中使用Promise,它看起来比递归干净得多。
const typewriter1 = document.getElementById('typewriter1');
const typewriter2 = document.getElementById('typewriter2');
const name = 'Alim Bolar';
const address = "Some part of the world";
const currentLocation = "Bali, Indonesia";
const profile = "Frontend Development, Backend Development, WordPress Development"
let prom = Promise.resolve();
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
function typeField(textToInsert, element) {
prom = prom.then(async () => {
for (const char of textToInsert) {
element.textContent += char;
await delay(500);
}
});
}
typeField(name, typewriter1);
typeField(address, typewriter2);
<header>
<div>NAME : <span id="typewriter1"></span></div>
<div>ADDRESS : <span id="typewriter2"></span></div>
</header>
相关文章