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

124
Vistas
loop in js, but wait till current iteration is done, then get to next

My goal is to execute a function that can print number 1-4; But in 1s intervals (and I don't want to use setInterval). I've been trying and what I could do was to print all the elements in an array after one second delay. here's the code :

const wait = async (number) => {
  return new Promise(async(resolve)=>{
    setTimeout(async()=>{
      resolve();
    },number);
  })
}

const listElement = document.getElementById("list");

[1,2,3,4].map((num)=>{
  const newListItemElement = document.createElement("li");
  newListItemElement.innerHTML = num;
  wait(1000).then(()=>{
    console.log(num);
    listElement.appendChild(newListItemElement);
  })
})
<html>
<body>
  <h3>list</h3>
  <ul id="list">
  </ul>
</body>
</html>

What I want this to do is to wait a second and print 1 then wait a second and print 2 and so on. The code I added in the snippet is making all the numbers appear together at once and this is because map function goes on even if the current iteration isn't done yet.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do this using setTimeout

const listElement = document.getElementById("list");

[1, 2, 3, 4].forEach((num) => {
  setTimeout(() => {
    const newListItemElement = document.createElement("li");
    newListItemElement.innerHTML = num;
    listElement.appendChild(newListItemElement);
  }, num * 1000);
})

const listElement2 = document.getElementById("list2");

// use this if you are looping over an array of data instead of array of numbers
[1, 2, 3, 4].forEach((num, index) => {
  setTimeout(() => {
    const newListItemElement = document.createElement("li");
    newListItemElement.innerHTML = num;
    listElement2.appendChild(newListItemElement);
  }, (index + 1) * 1000);
});
<body>
  <h3>list</h3>
  <ul id="list">
  </ul>
    <h3>list 2</h3>
  <ul id="list2">
  </ul>
</body>

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