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

166
Visualizações
how to use both timeout and break inside for loop in javascript

As per below code timeout not working properly how to solve this problem.

for (let i = 0; i < 4; i++) {
  if (socket.isConnected() == true) {
    connectCall([]);
    break;
  } else {
    setTimeout(() => {
      console.log("Call-1:");
    }, 1000);
  }
}

Here SetTimeout not working properly every time hold for some time. my concern is that when condition is match break loop and not match then hold for some time.if any other way to done it then please send me proper solution. if its done from while loop or any other loop then its also accepted.

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

0

setTimeout is working properly, it delays the execution of the console.log for 1 second but this is happening asynchronous.

As you can see in this example all logs happen directly after 1 second:

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

If you want to "sleep" for one second in your loop you have to wait for the setTimout.

You can do this with a Promise for example:

(async () => {
  const socket = {
    isConnected: () => false
  }

  for (let i = 0; i < 4; i++) {
    if (socket.isConnected()) {
      connectCall([]);
      break;
    } else {
      await new Promise(res => {
        setTimeout(() => {
          console.log(`Call-${i}:`);
          res();
        }, 1000);
      });
    }
  }
})();

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