异步添加/删除字符串
实现一个打字机打印一段字符串,然后删除,打印新的字符串,删除的效果。 利用 await实现字符串的截取,async 函数执行时,如果遇到 await 就会先暂停执行 ,等到触发的异步操作完成后,恢复 async 函数的执行。利用async 函数返回一个 Promise 对象,实现字符的添加。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>打字机</title>
<style>
*{
padding:0px;
margin:0px;
}
body{
width: 100%;
height:100vh;
background-color: #222;
display: flex;
flex-direction: column;
justify-content:center;
align-items:center;
}
.word{
margin-top: 30px;
color:#fff;
font-size:15px;
}
.guanbiao{
color:#fff;
animation: guanbiao 1s infinite;
}
@keyframes guanbiao{
0%{
color: #fff;
}
100%{
color: transparent;
}
}
</style>
</head>
<body>
<div class="text">
<span class="word">
</span>
<span class="guanbiao">|</span>
</div>
<script>
let sentence=["城市夜晚的纽带都是灯红酒绿","懒惰与欲望逼你每天走在悬崖峭壁","你松开手 不再理会周围虚情假意","同时许诺明天一定加足十万马力","要我说不如现在就迈一步,在迷路的同时领悟,不正的心术无法驱散前路的迷雾,享受并与世无争。"];
let show=document.querySelector('.word');
function setText(t){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
show.innerHTML=t;
resolve();
},100)
})
}
async function main(flag,word){
if(flag==1){
for(let i=0;i<=word.length;i++){
await setText(word.substr(0,i));
}
setTimeout(()=>{
main(!flag,word);
},2000)
}else{
for(let i=word.length;i>=0;i--){
await setText(word.substr(0,i));
}
setTimeout(()=>{
main(!flag,sentence[++j]);
if(j==(sentence.length-1)){
j=-1;
}
},2000)
}
}
let j=0;
main(1,sentence[j]);
</script>
</body>
</html>