javascript - 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 行之后执行。最好的方法是什么?
解决方案
首先想到的是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>
推荐阅读
- php - 带有 apache 虚拟端口的 phpCHART 不起作用
- python - 错误:错误:(-215:断言失败)samples.cols == var_count && samples.type() == 5 in function 'cv::ml::SVMImpl::predict'
- sql - 复杂的SQL查询帮助请
- error-handling - 如何处理 nuxtjs 插件中的 axios onError 并向用户显示适当的错误消息
- database - 数据管道,用于通过相互非循环依赖的模块运行数据记录
- javascript - 如何用JS添加类
- symfony - 导出导入的宏
- javascript - 单击下一个/上一个链接时如何关闭菜单?
- c# - Datagrid 视图 - 无法对数据进行排序
- sql - 我应该在哪里输入 DISTINCT?