Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
Adding different texts to html periodically using javascript

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

  • Create a counter variable with value 0
  • Each time when the setInterval function executes, update the value with the value got after division by 3.
  • Increment the value each time the function executes.
  • This ensures the counter always stay between 0 and 3.
  • This help you to access each index one by one when the setInterval function executes

let 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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda