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

117
Visualizações
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 Respostas
Responde à pergunta

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