Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following JS functions:

function checkIfGameAlreadyStarted(){
    $.get("IsGameAlreadyStarted",null,function(gameAlreadyStarted){
        if (gameAlreadyStarted == "true"){
            window.location = "index.jsp?content=game";       
        } else{
            alert("bla");
        }  
    });
}

function joinGame(playerForm){
    $.get("GenerateClientID",null,function(clientID){         
        $.get("JoinGame",{
            "NAME" : playerForm.elements[0].value,
            "ID" : clientID
        }
        ,function(gameParam){

            $("#waitingContainer").append("You have joined the game!<br>Waiting for game creator to start game..");
            setInterval(checkIfGameAlreadyStarted(), 1000);    

        });
    });
}

Why does setInterval executes checkIfGameAlreadyStarted only once, and not every second?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
451 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are passing the result of executing the function instead of the function itself. Since the result of the function is undefined, you are executing checkIfGameAlreadyStarted and then passing undefined to setInterval which doesn't do anything.

Instead of this:

setInterval(checkIfGameAlreadyStarted(), 1000);

Your statement should be this:

setInterval(checkIfGameAlreadyStarted, 1000);

without the parentheses at the end of the function name.

When you pass checkIfGameAlreadyStarted() that calls the function immediately and gets it's return value. When you pass checkIfGameAlreadyStarted that passes a reference to the function so setInterval can call it later (which is what you want).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...