I am trying to add text from an array to html. I will take one word at a time from array and add it to the html and i want to stay that word in html for 5 second then clear that word and add the next word from the array to html.
I tried it for one and half hour to get this done. but i can't figure it out how
below is my sample code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div>
<h1>Hello</h1>
<span id="change-text"></span>
</div>
<script>
let texts = ["Alexa", "siri", "Google"]
let text = document.getElementById("change-text");
setInterval(() => {
texts.forEach((element) => {
text.innerText = element;
});
}, 5000);
</script>
</body>
</html>
I am newbie to javascript, i tried setInterval and forEach to do but i messed up.
Dont use loop inside a setInterval function, instead use a counter.
Whats the issue with the code?
You are making use of Array.forEach inside setInterval function. What this does is it loops throuh the array each time when the interval counts, Since you are overwriting the conter of your DOM, it first writes the first element in the array that is "Alexa". Next it updates the same element with "siri" and then with "Google". These three updates happen each time when the function inside setInterval is executed. You will only see the result of last itration, that is "Google", that why your DOM node is always "Google".
How to fix this issue?
You have to update the logic. The logic should be like that the DOM update should happen only once per setInterval function execution. I followed the below logic.
counter variable with value 0setInterval function executes, update the value with the value got after division by 3.setInterval function executeslet texts = ["Alexa", "siri", "Google"]
let text = document.getElementById("change-text");
let index = 0;
setInterval(() => {
index %= 3;
text.innerText = texts[index];
index++;
}, 1000);
<h1>Hello</h1>
<span id="change-text"></span>