我用JavaScript创建了一个类型编写器效果,但是我想当单词更改在函数增加索引之前添加延迟
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, 400);
}());
<span>I'm <span class="typing"></span></span>
答案 0 :(得分:0)
尝试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>
答案 1 :(得分:0)
这里是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>