Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda