繁体   English   中英

Javascript 中的打字机效果用于多个文本

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM