Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!