0

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"

0 Answers0