index++时添加延迟(增加)

我用 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>


江户川乱折腾
浏览 69回答 2
2回答

不负相思意

尝试return不同的timeoutconst texts = ["Front Developer", "Designer", "Human"];let count = 0;let index = 0;let currentText = '';let letter = '';(function type() {&nbsp; if (count === texts.length) {&nbsp; &nbsp; count = 0;&nbsp; }&nbsp; currentText = texts[count];&nbsp; letter = currentText.slice(0, index++);&nbsp; document.querySelector('.typing').textContent = letter;&nbsp; if (letter.length === currentText.length) {&nbsp; &nbsp; count++;&nbsp; &nbsp; index = 0;&nbsp; &nbsp; setTimeout(type, 2000);&nbsp; &nbsp; return;&nbsp; }&nbsp; setTimeout(type, 200);}());<span>I'm <span class="typing"></span></span>

繁星点点滴滴

这里有一个解决方案async / awaitconst texts = ["Front Developer", "Designer", "Human"];let count = 0;let index = 0;let currentText = '';let letter = '';(async function type(){&nbsp; &nbsp; if(count === texts.length){&nbsp; &nbsp; &nbsp; &nbsp; count = 0;&nbsp; &nbsp; }&nbsp; &nbsp; currentText =&nbsp; texts[count];&nbsp; &nbsp; letter = currentText.slice(0, index++);&nbsp; &nbsp; document.querySelector('.typing').textContent = letter;&nbsp; &nbsp; if(letter.length === currentText.length){&nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; index = 0;&nbsp; &nbsp; &nbsp; &nbsp; await sleep(4000);&nbsp; &nbsp; }&nbsp; &nbsp; await sleep(30);&nbsp; &nbsp; type();}());function sleep(time) { return new Promise(res => setTimeout(res, time))}<span>I'm <span class="typing"></span></span>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript