I want to create a function to animate text like typewriter. I can't understand why words[index].length
is returning undefined in setInterval funcation.
let speed = Math.floor(Math.random() * 1000);
function typeWriter() {
let words = ["Achieve", "Attain"]; /* The text */ // 6
let typeWriter = document.getElementById("typewriter");
let i = 1;
let index = 0;
while (index < words.length) {
setInterval(() => {
if (i <= words[index].length && i > 0) {
typeWriter.innerHTML = words[index].slice(0, i);
if (i == words[index].length) {
i = -1;
}else {
i++;
}
} else if ((i * -1) <= words[index].length && i < 0) {
typeWriter.innerHTML = words[index].slice(0, i);
if ((i * -1) == words[index].length) {
clearInterval();
}else {
i--;
}
}
speed = Math.floor(Math.random() * 1000);
}, speed);
if (index == words.length) {
index = 0;
} else {
index++
}
}
}