<!--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>打字機(jī)效果</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>
走同樣的路,發(fā)現(xiàn)不同的人生
The problem lies in the lp() function
if(value>0){
writecontext.innerHTML=context.slice(0,contextLength--)+'_'
lp()
}else{...}
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 youlp
函數(shù)其實(shí)是無(wú)限循環(huán)函數(shù)來(lái)的,需要把lp
函數(shù)下的contextLength--
改為value--
,且需要把value > 0
改為value >= 0
var context='這個(gè)程序是想先輸逐個(gè)出所有文字,三秒鐘以后逐個(gè)刪除所有文字,但是運(yùn)行以后發(fā)現(xiàn)刪除到頭又會(huì)重新刪除一遍,請(qǐng)大神幫忙看看,謝謝!';
var contextLength=Number(0)
var writecontext=document.querySelector('#main')
var t1,t2;
t1 = setInterval('write()',100);
function write(){
if(contextLength<=context.length){
writecontext.innerHTML=context.slice(0,contextLength++)+'_'
}
else{
clearInterval(t1);
setTimeout(function(){
t2 = setInterval('clear()',100);
},1000);
}
}
function clear(){
if(contextLength>=0){
writecontext.innerHTML=context.slice(0,contextLength--)+'_'
}else{
clearInterval(t2);
}
}