首页 > 解决方案 > Javascript中的打字机效果用于多个文本

问题描述

这是我的 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”。然后,它应该在类型编写器效果中添加“这很有趣”。我希望 line2 仅在第 1 行之后执行,第 3 行仅在第 2 行之后执行。最好的方法是什么?

标签: javascript

解决方案


首先想到的是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>


推荐阅读