如何等待使用setTimeout递归调用的函数完成? [英] How to wait for a function, which calls itself recursively with setTimeout, to complete?
问题描述
我是Java语言的新手,目前正在一个网站上工作,随着时间的推移,它会改变其外观.
I am new to Javascript and currently working on a website, that changes how it looks by itself over time.
该页面的一部分是打字机",它逐个字母地写出文本.这是此打字机的代码:
One part of this page is a "Typewriter", that writes out a text letter by letter. This is the code for this Typewriter:
function typeWriter(element, txt) {
if (txt.length > 1) {
element.textContent += txt.charAt(0);
var newText = txt.slice(1,txt.length);
setTimeout(typeWriter, 150 , element, newText);
} else {
element.textContent += txt.charAt(0);
}
}
现在,我要等打字机功能完成其文字,然后再进行另一次更改,例如我的背景色.
Now I want to wait for the typewriter-function to finish with its text before doing another change to let's say my background-color.
function runThis(){
var line1 = document.getElementById("line1");
typeWriter(line1, "This should be written first, before continuing");
document.body.style.backgroundColor = "blue";
}
据我所知,setTimeout使我的打字机异步运行,因此,如果我按照上面的示例中的操作进行操作,则当打字机击中第一个setTimeout时,第三行代码将立即运行.
To my understanding, the setTimeout makes my typewriter async, so if I do it as in the example above the third line of code will run as soon as the typewriter hits the first setTimeout.
我试图通过异步/等待条款和承诺来实现这一点.但是,即使在我兑现了诺言之后,我的"runThis"还是打字机完成后,功能将无法继续.
I tried to realize this with the async/await terms and promises. But even after I resolve the promise, my "runThis" function won't continue after the typewriter finishes.
function typeWriter(element, txt) {
return new Promise (function(resolve,reject) {
if (txt.length > 1) {
element.textContent += txt.charAt(0);
var newText = txt.slice(1,txt.length);
setTimeout(typeWriter, 150, element, newText);
} else {
element.textContent += txt.charAt(0);
resolve();
}
})
}
async function runThis() {
var line1 = document.getElementById("line1");
await typeWriter(line1, "papupa");
console.log("waiting over")
document.body.style.backgroundColor = "blue";
}
能否请您帮我弄清楚这里出了什么问题?非常感谢
Can you please help me figure out what's wrong here? Thank you very much
推荐答案
您可以将 setTimeout
包装在promise中.这将使您可以使用 async/await
语法更清楚地表达代码的意图,就像在同步运行一样.
You can wrap the setTimeout
in a promise. This will allow you to use the async/await
syntax to express the intention of your code more clearly, almost as if it was running synchronously.
async function runThis() {
var line1 = document.getElementById("line1");
await typeWriter(line1, "papupa");
document.body.style.backgroundColor = "blue";
}
async function typeWriter(element, txt) {
for (var i = 0; i < txt.length; i++) {
element.textContent += txt[i]; // this is shorthand for txt.charAt(i)
await pause();
}
}
function pause() {
return new Promise(function(resolve, reject) {
setTimeout(resolve, 150);
});
}
这篇关于如何等待使用setTimeout递归调用的函数完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!