Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

javascript - Stop auto type at last array


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Currently your functions keep calling each other without any signal to stop somewhere. You already keep track of where your index currently is in the textArray with textArrayIndex. Use that to see if the end has been reached in the else statement of your type function.

if (textArrayIndex < textArray.length - 1) {
  setTimeout(erase, newTextDelay);
}

Here it checks if the current index is lower than the last index of the array. If it is, it will continue to call the erase function and increment textArrayIndex with 1 there. Otherwise when the index is not lower than the last index, meaning it's the last one, it will simply do nothing, thus breaking the loop.

const typedTextSpan = document.querySelector(".typed-text");
const cursorSpan = document.querySelector(".cursor");
const textArray = ["reconnaitre un talent ?", "détécter une opportunité ?"];
const typingDelay = 170;
const erasingDelay = 100;
const newTextDelay = 2000;
let textArrayIndex = 0;
let charIndex = 0;

function type() {
  if (charIndex < textArray[textArrayIndex].length) {
    if (cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing");
    typedTextSpan.textContent += textArray[textArrayIndex].charAt(charIndex);
    charIndex++;
    setTimeout(type, typingDelay);
  } else {
    cursorSpan.classList.remove("typing");
    
    // Erase if the end has not yet been reached.
    if (textArrayIndex < textArray.length - 1) {
      setTimeout(erase, newTextDelay);
    }
  }
}

function erase() {
  if (charIndex > 0) {
    if (!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing");
    typedTextSpan.textContent = textArray[textArrayIndex].substring(0, charIndex - 1);
    charIndex--;
    setTimeout(erase, erasingDelay);
  } else {
    cursorSpan.classList.remove("typing");
    textArrayIndex++;
    setTimeout(type, typingDelay + 1100);
  }
}

document.addEventListener("DOMContentLoaded", function() {
  if (textArray.length) setTimeout(type, newTextDelay + 250);
});
<div class="container" id="container">
  <h1>Savez-vous <span class="typed-text" id="typed-text"></span><span class="cursor" id="cursor">&nbsp;</span></h1>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...