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

203
Visualizações
function invoked for each element in array, in time intervals

Trying to write a function, that does work for one element in the array - and after time, repeats the same work for the next element (for each element in the array). Array consists of <span> elements.

Current function does work for all the elements in the same time.

const wordIntroGroup = document.getElementsByClassName("word");
const forwardBut = document.getElementById("forward");

forwardBut.addEventListener("click", forward);


function forward() {

  const y = wordIntroGroup;

  for (let i = 0; i < y.length; i++) {
    setTimeout(function() {
      console.log(y[i]);
    }, 2000)
  }
}
<p>
  <span class="word">Naw,</span>
  <span class="word">while</span>
  <span class="word">you're</span>
  <span class="word">here</span>
</p>

<span id="forward" class="material-icons">
  fast_forward
</span>

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

0

Your for loop runs every call of your setTimeout function at the same time. So everything will occur 2000ms after the for loop runs. The simplest solution would be to extend the setTimout duration by that of the current location in the array.

setTimeout(function (){
     console.log(y[i]);
}, 2000*i) // multiply your duration by i, the index of your current element in the array

Also your syntax error is you didn't close the function forward at the end of your script

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