2011-10-12 116 views
17

我有以下的JS功能:JS setInterval的执行只有一次

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);  

     }); 
    }); 
} 

为什么setInterval执行checkIfGameAlreadyStarted只有一次,而不是每一秒?

回答

56

您正在传递函数的执行结果,而不是函数本身。由于该函数的结果是未定义的,因此您正在执行checkIfGameAlreadyStarted,然后将undefined传递给setInterval,该setInterval不执行任何操作。

取而代之的是:

setInterval(checkIfGameAlreadyStarted(), 1000); 

你的说法应该是这样的:

setInterval(checkIfGameAlreadyStarted, 1000); 

没有在函数名末尾括号。

当您通过checkIfGameAlreadyStarted()立即调用该函数并获取它的返回值。当您通过checkIfGameAlreadyStarted传递给函数的引用时,setInterval可以稍后调用它(这是您想要的)。