2 回答

TA貢獻1777條經(jīng)驗 獲得超10個贊
嘗試return不同的timeout
const texts = ["Front Developer", "Designer", "Human"];
let count = 0;
let index = 0;
let currentText = '';
let letter = '';
(function type() {
if (count === texts.length) {
count = 0;
}
currentText = texts[count];
letter = currentText.slice(0, index++);
document.querySelector('.typing').textContent = letter;
if (letter.length === currentText.length) {
count++;
index = 0;
setTimeout(type, 2000);
return;
}
setTimeout(type, 200);
}());
<span>I'm <span class="typing"></span></span>

TA貢獻1803條經(jīng)驗 獲得超3個贊
這里有一個解決方案async / await
const texts = ["Front Developer", "Designer", "Human"];
let count = 0;
let index = 0;
let currentText = '';
let letter = '';
(async function type(){
if(count === texts.length){
count = 0;
}
currentText = texts[count];
letter = currentText.slice(0, index++);
document.querySelector('.typing').textContent = letter;
if(letter.length === currentText.length){
count++;
index = 0;
await sleep(4000);
}
await sleep(30);
type();
}());
function sleep(time) { return new Promise(res => setTimeout(res, time))}
<span>I'm <span class="typing"></span></span>
添加回答
舉報