<!--Please copy and paste the code below and run it in the browser to see the problem-->
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>打字机效果</title>
<style>
#main{
border: 1px solid #ccc;
height:100px;
width:1000px;
}
</style>
</head>
<body>
<p id='main'></p>
<script type="text/javascript">
var context='This program wants to input all the text one by one first, and then delete all the text one by one after three seconds. However, after running it, it is found that it will be deleted again after deletion. Please help me, thank you! '
//console.log(a.length)
var contextLength=Number(0)
var writecontext=document.querySelector('#main')
function loop(){
return new Promise(function(sol,rej){
function lop(){
var t=setTimeout(function(){
if(contextLength<context.length){
writecontext.innerHTML=context.slice(0,contextLength++)+'_'
lop()
}
else{
if(contextLength=context.length){
setTimeout(function(){
clearTimeout(t)
sol(contextLength)
},3000)
}
}
},200)
}
lop()
})
}
loop().then(function(value){
function lp(){
var n=setTimeout(function(){
if(value>0){
writecontext.innerHTML=context.slice(0,contextLength--)+'_'
lp()
}else{
if(value<=0){
clearTimeout(n)
}
}
},50)
}
lp()
})
</script>
</body>
</html>
The problem lies in the lp() function
What is judged here is value but the operation is contextLength, so the lp() function causes an infinite loop.
Explain the reason for deleting twice: mainly the slice() method
'string'.slice(0,n);
When n is a positive number, it is executed in the normal order; when n is a negative number, n will be replaced by the string length + n during execution. See MDN for details.
So, after the first execution of lop() deletes the string to 0, the contextLength continues to decrease by one, resulting in two visual deletions
Written by you
lp
函数其实是无限循环函数来的,需要把lp
函数下的contextLength--
改为value--
,且需要把value > 0
改为value >= 0
Save the words into an array, and then add and delete the array