[英]Typewriter Effect in Javascript for multiple texts
這是我的 Javascript 函數。 我的目標是,無論何時我將文本傳遞給它,它都應該在打字機效果的 div 中顯示文本。
function typeWriter(txt) {
if (i < txt.length) {
console.log(i);
maindiv.innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter,50,txt);
}
}
這是我的 main() 函數
function main() {
typeWriter("Hello World."); //line1
i=0;
console.log("Hello World just got entered"); //line2
i=0;
typeWriter("This is fun."); //line3
}
發生了什么在第一個文本中的“H”被顯示后,控制被傳遞到第 2 行,然后是第 3 行,依此類推。
我想要什么: div 應該首先在打字機效果中顯示“Hello World”。 然后,它應該在類型編寫器效果的 div 中添加“這很有趣”。我希望 line2 僅在第 1 行之后執行,並且僅在第 2 行之后執行第 3 行。解決這個問題的最佳方法是什么?
首先想到的是Promises。 為了使事情變得更加困難,您需要按順序執行承諾。
const mainDiv = document.querySelector(".main-div") // wrap timeout in a promise function type(c, ms) { return new Promise(resolve => { setTimeout(() => { mainDiv.innerHTML += c; resolve() }, ms) }) } // execute promises sequentially async function typeWriter(txt, ms) { const characters = txt.split("") // for loop is key, forEach would not work for (var i = 0; i < characters.length; i++) { await type(characters[i], ms) } } // await each asynchronous function async function main() { const ms = 500; await typeWriter("Hello, ", ms) await typeWriter("World", ms) } main()
<div class="main-div"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.