0

I'm trying to get rid of this loop and cannot find the issue.

I'm using websocket for sending some message , I'm using switch/case statement for calling some functions, Here the code.

var var_wait_on_buzzer = false;
var var_wait_for_answer = false;       
 ws.onmessage = (event) =>{
            console.log("[Message received from server]", event.data)
            stuff += "<br /> msg recv ["+event.data+']';            
            document.getElementById("h").innerHTML=stuff;
            let json_obj = JSON.parse(event.data);
            console.log(event.data)
            switch (json_obj.id) {
                case "new_question": 
                    wait_on_buzzer();
    function new_question(){ 
        try {
            var_wait_on_buzzer = false;
            var new_question = document.getElementById("player_text");
            new_question.textContent = "New Question, waiting for an Answer";               
            ws.send(JSON.stringify({     
                id : "new_question",
            }));
            console.log("Msg sent:new question ");
            var_wait_on_buzzer = true;
            console.log("var var_wait_on_buzzer: "+ var_wait_on_buzzer)
            return;
        }
        catch (error) {
            console.log("Msg sent:error new_question - " + error)
        }
    }


    function wait_on_buzzer() {
        if (var_wait_on_buzzer === true){
            console.log("here")
            ws.onmessage = (player_msg) => {
                console.log(player_msg.data) 
                let json_obj = JSON.parse(player_msg.data);
                //if (json_obj.id == "buzzer"){
                    console.log("var var_wait_on_buzzer: "+ var_wait_on_buzzer)
                    var id = document.getElementById("player_text");
                    player_name = json_obj.data
                    id.textContent = json_obj.data + " buzzed, is it the correct answer?";                        
                    var_wait_on_buzzer = false;
                    console.log("var var_wait_on_buzzer: "+ var_wait_on_buzzer)                            
                //}                    
            }
            return;
        }            
    }

The problem is I'm stucked inside wait_on_buzzer loop, I switched form try/catch to if statement , return doesn't break the loop , I don't understand why

Here is the console output :

here

test31.html:53 {"id": "buzzer", "data": "player1"}

test31.html:56 var var_wait_on_buzzer: true

test31.html:61 var var_wait_on_buzzer: false

test31.html:53 {"id": "buzzer", "data": "player2"}

test31.html:56 var var_wait_on_buzzer: false

test31.html:61 var var_wait_on_buzzer: false

as we can see var_wait_on_buzzer is still false so the program is stuck in "ws.onmessage = (player_msg)"

Can you help me please ?

0

You must log in to answer this question.

Browse other questions tagged .