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

176
Vistas
JavaScript: Wait in a if else loop in correct order

I had used setTimeout(), sleep function, async and await but all of them will ruin my output order and ruin my loop. They all kinda keep doing things on the timeline until it meets the time and then do back the previous counting items. This is annoying that I hope the sequence of output can be kept, otherwise all my update chat will be messed up. Help me!!!

my code:

class Chatbox {
    constructor(){
    ...
    }
    updateChat(chatbox) {
        const Message = this.messages.slice()
        allMessage.forEach(function(item,index) {
           //it will go "else" first then do "if" then do "else"-> "if" -> "else"...
           if (item.name === "Sam")
              {   
                    console.log("3");
                if (True){
                    console.log("4");
                }
                else{
                    console.log("4");
                }
                //wait 2 seconds
                console.log("5");
              }
            else
            {   
                console.log("1");
                //wait 2 seconds
                console.log("2");
            }}}}

my expectation:

"1"    //first message (loop)
wait 
"2" 
"3" 
"4" 
wait 
"5"    //second message (loop)
"1" 
wait 
"2" 
"3" 
"4" 
wait 
"5" 

Actual output if using setTimeout():

"1"    //first message (loop)
"3" 
"4" 
"2" 
"1"    //while waiting output "5", it already start the second loop 
"5"  
"3" 
"4" 
"2" 
"1"   //while waiting output "5", it already start the second loop which output "1"
about 4 years ago · Juan Pablo Isaza
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