I want the first text to be printed first, and then after finishing printing the first text; The second text will start to be printed.
In the code I wrote, the first text is printed well, but the second text is not printed for me.
Also, I tried hard to apply a sign (|) while printing each word to convey the feeling of typing to the user, but I couldn’t make it work. Please guide me in this matter as well.
My codes:
const text1 = "Your first sentence here"; // Enter your first sentence here
const text2 = "Your second sentence here"; // Enter your second sentence here
let i = 0;
let isFinished = false;
function typeSentence(text, element) {
const interval = setInterval(() => {
if (i === text.length) {
clearInterval(interval);
isFinished = true;
if (element === $('#loading-text')) {
// Check if the first sentence is finished
if (isFinished) {
// Start typing the second sentence after finishing the first sentence
i = 0;
typeSentence(text2, $('#loading-text2'));
}
}
} else {
element.text(element.text() + text[i]);
i++;
}
}, 100); // Speed of animation (adjust as needed)
}
typeSentence(text1, $('#loading-text'));
#loading-text, #loading-text2 {
font-size: 24px;
font-weight: bold;
text-align: center;
margin: 20px auto;
width: 50%;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="loading-text"></div>
<div id="loading-text2"></div>
2
Answers
you can simplify your code and juste call typeSentence for second text if it have not been already call
Here is a simpler and somewhat DRYer version using interval