'how to use setTimeout on a function in javascript
I am trying to create a typing effect using javascript however the text is not readable because it's too fast. I really need a way to make my function pause in every sentence.
const texts = ["get a quote", "get a Tweet"];
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.getElementById("welcome").textContent = letter;
if (letter.length === currentText.length) {
count++;
index = 0;
}
setTimeout(type, 100)
};
type()
<div id="welcome"></div>
Solution 1:[1]
you can try this instead, it gives a different delay to the setTimeout function in the case of a new sentence:
const texts = ["get a quote", "get a Tweet"];
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.getElementById("welcome").textContent = letter;
if (letter.length === currentText.length) {
count++;
index = 0;
setTimeout(type, 1000);
} else {
setTimeout(type, 100);
}
}
type();
Solution 2:[2]
Here's a slightly modified version of your code that doesn't require any global variables, and introduces a two second pause between each line of text.
It uses a loop to extract the first letter of each sentence, adds that to the element textContent, and then passes the remaining letters back to the function using a setTimeout. If there are no letters left in the sentence, another setTimeout is called after two seconds, resetting the textContent, and then calling the loop again with the next sentence in the array.
const texts = ["get a quote", "get a Tweet"];
const div = document.querySelector('div');
function type(texts) {
// The index initially points to the
// first array element
let index = 0;
function loop(str) {
// If the string still has letters
if (str.length) {
// Destructure the first letter from it
// add assign all the other letters to `rest`
const [ letter, ...rest ] = str;
// Add the letter to the textContent
div.textContent += letter;
// Then call the function again with the
// rest of the letters
setTimeout(loop, 100, rest);
// If there are no letters left increase the index,
// check to see if the array has that index,
// then, after two seconds, reset the textContent
// and call the function again with a fresh sentence
} else {
++index;
if (index < texts.length) {
setTimeout(() => {
div.textContent = '';
loop(texts[index]);
}, 2000);
}
}
}
loop(texts[0]);
}
type(texts);
<div id="welcome"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amine BENETTAJ |
| Solution 2 |
