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

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

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