Java脚本:如何查找setInterval函数现在正在运行还是超时?

mri*_*dul 1 javascript setinterval

在我的项目中,我使用了两个setInterval函数,一个函数一直在运行.第二个功能是根据键盘输入动态启动和停止.如何找到第二个setInterval函数的状态(Running或Timeout)?

    setInterval(function()
            {
            if(//want to check state of seInterval Function fire)
                      {
                       //somecode
                      }
            },300);
  var fire=setInterval(function()
            {
                     // some code
            },300);
Run Code Online (Sandbox Code Playgroud)

Pra*_*een 7

最好在setInterval中为方法添加boolean变量isRunning.根据它切换值.使用该值可以跟踪状态.

根据您发布的代码:

isFirstInstanceRunning =true;
isSecondInstanceRunning = false;
setInterval(function() {
    //want to check state of seInterval Function fire
    if(isFirstInstanceRunning){
        //somecode
    }
},300);

//--- Pass a boolean parameter as "true" onKeypress     
function startSecondInstance(toCheck) {     
    var fire=setInterval(function() {
        //want to check state of seInterval Function fire
        if(toCheck){
            //somecode
        }
    },300);
}

//---Similarly when you stop the second method
function stopSecondInstance() {
    clearInterval(fire);
    isSecondInstanceRunning = false;
}
Run Code Online (Sandbox Code Playgroud)

  • 显然我们认为变量名称相似:D +1 (2认同)