JS setInterval executes only once

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

I have the following JS functions:

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


        
2条回答
  •  盖世英雄少女心
    2020-11-28 13:54

    To use checkIfGameAlreadyStarted without parameters, use the method below:

    setInterval(checkIfGameAlreadyStarted, 1000);
    

    In case checkIfGameAlreadyStarted has some parameters to be passed, use the method below:

    setInterval(function(){checkIfGameAlreadyStarted(a,b);},1000)
    

    This is the best approach I have seen. Other well tested methods are welcomed ,though.

    Edit

    Passing parameters after the timeout as suggested in the comments is cool but using the above method I stated helps to combat the bind this problem in case checkIfGameAlreadyStarted() is a class method like this this.checkIfGameAlreadyStarted().

    In case you want to pass parameters after timeout, here is how it works,

    setInterval(checkIfGameAlreadyStarted, 1000, parameter1, parameter2);
    

提交回复
热议问题