本文介绍了JS setInterval只执行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JS函数:

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 只执行一次,而不是每一次?

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

推荐答案

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

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.

而不是:

setInterval(checkIfGameAlreadyStarted(), 1000);

您的陈述应为:

setInterval(checkIfGameAlreadyStarted, 1000);

在函数名末尾没有括号。

without the parentheses at the end of the function name.

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

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

这篇关于JS setInterval只执行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:16