JS setInterval executes only once

前端 未结 2 1017
遥遥无期
遥遥无期 2020-11-28 13:38

I have the following JS functions:

function checkIfGameAlreadyStarted(){
    $.get(\"IsGameAlreadyStarted\",null,function(gameAlreadyStarted){
        if (ga         


        
2条回答
  •  被撕碎了的回忆
    2020-11-28 14:13

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

提交回复
热议问题