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

192
Visualizações
How can setTimeout run in order

I have two for loop, inside them I have setTimeout function like following code:

for(let i=0;i<3;i++){
    setTimeout(()=>{console.log(i)}, 1000)
}
for(let i=0;i<3;i++){
    setTimeout(()=>{console.log(i)}, 1000)
}

i want the second loop does not executed until after the first loop finished,

I want this result:
0
1
2
0
1
2
- and between 2 numbers wait 1 second.

how i can do that?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

I can't comment yet or I would ask clarifying questions so I'll give you what I think you're asking for. If you want a 1 second delay between each number being logged to the console then this will work:

const func = async () => {
  for (let i = 0; i < 3; i++) {
    await new Promise((resolve) =>
      setTimeout(() => {
        console.log(i);
        resolve();
      }, 1000)
    );
  }
  for (let i = 0; i < 3; i++) {
    await new Promise((resolve) =>
      setTimeout(() => {
        console.log(i);
        resolve();
      }, 1000)
    );
  }
};

func();

A quick rundown of what's happening here. I created an outer function named func which I made asynchronous so that I can use the await keyword within it. I then put the setTimeout call inside a new instance of Promise. The promise combined with the await means that javascript will essentially stop at that line until the Promise calls resolve. Once resolve is called that instance of Promise is finished and the await statement stops "blocking" javascript and the callbackque continues. TLDR:

  1. To use await you must be in an asynchronous function.
  2. If await is used in front of a Promise everything will stop until the promise resolves.
  3. Placing the resolve of the promise inside the callback given to setTimeout ensures that we will wait until each timeout finishes BEFORE the next timeout begins.
about 4 years ago · Santiago Trujillo Relatório

0

I think that you're trying to do sort of a counter

Try something like this:

for(let i=1;i<=3;i++){
   setTimeout(()=>{ console.log(i)}, i*1000 )
}

Let me know if this solve your problem

about 4 years ago · Santiago Trujillo Relatório

0

This will work

nxt (0, 0);//seed the stack
function nxt(num, itertn){
    if(num == 3){//want till 2
        if(itertn == 0){// first or 2nd iteration
            num =0;
            itertn++;
        }else{
            return;//after 2nd stop
        }
    }
    console.log(num);//the work
    num++;    
    setTimeout(nxt, 1000, num, itertn);//next after a second
}

But there are other ways to do this

about 4 years ago · Santiago Trujillo 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