我需要让这些字母中的每一个字母都级联出现,就像在旧的电子游戏中一样。我将每个字母保存在一个数组中,函数writeText可以将所有字母都放在对话框中。这可行,但是我希望每个字母在很短的延迟后出现。如何使用超时来延迟它们?
const phrase1 = ['H', 'i', ',', ' ', 'J', 'o', 'n', 'a', 't', 'h', 'a', 'n'];
function writeText(phrase){
var dialogue= phrase[0];
for (i=1; i < phrase.length; i++){
dialogue= dialogue+ phrase[i];
document.getElementById("dbox").innerHTML = dialogue;
};
writeText(phrase1);
不是使用循环,而是使用超时,而是在渲染字母后调用writeText()
。
const phrase1 = ['H', 'i', ',', ' ', 'J', 'o', 'n', 'a', 't', 'h', 'a', 'n'];
function writeText(phrase) {
if (phrase.length === 0) return;
setTimeout(() => {
document.getElementById("dbox").innerHTML += phrase[0];
writeText(phrase.slice(1));
}, 200);
}
writeText(phrase1);
<div id="dbox"></div>
查看W3schools的这段代码https://www.w3schools.com/howto/howto_js_typewriter.asp
将函数async
和await
设置为虚拟Promise
:
async function writeText(phrase){
// your code here
const delayMs = 500; // set this to whatever you like
await new Promise(resolve => setTimeout(resolve, delayMs));
}