清除setTimeout里面立即调用的函数

时间:2014-01-17 09:20:27

标签: javascript function settimeout

 var a = function(bool){
       (function b(bool){
          if(bool === true || bool === undefined){
          console.log('running');
          setTimeout(b,50);
          }else{
           clearTimeout(b);
          }
       })();
   }

我已经知道这可能比setInterval好,但清除此功能不起作用。我已经尝试过break和return,并且它会一直循环遍历console.log

有关如何轻松取消此功能的任何建议吗?

我尝试过什么

        if(bool === true || bool === undefined){
          console.log('running');
          setTimeout(b,50);
          }else{
          return;
          }

        var d;
        if(bool === true || bool === undefined){
          console.log('running');
          d=setTimeout(b,50);
          }else{
           clearTimeout(d);
          }

1 个答案:

答案 0 :(得分:5)

clearTimeoutMDN)期望“timeoutID”而不是函数作为参数:

var id = setTimeout(b,50);
clearTimeout(id);

但是,当我仔细查看您的代码时,似乎还有另一个问题:

setTimeout(b,50);

您正在调用b而没有任何参数,因此函数参数bool将始终为undefined!试试这个:

setTimeout(function () {
    b(false);
},50);

然后它应该只迭代一次。然后你根本不需要清除超时(你只是停止设置新的超时):

var a = function(bool){
       (function b(bool){
          if(bool === true || bool === undefined){
              console.log('running');
              setTimeout(function () {
                  var goOn = false; //<--- abort condition here
                  b(goOn);
              },50);
          }
       })();
   }

现在你只需弄清楚你的中止条件是什么,并把它带到正确的地方。

编辑(回答您的评论)

看起来你只想要一个启动间隔的函数和一个停止它的函数。所以接下来是这种设置的最小例子(也计算迭代次数)。根据自己的需要调整它应该相当容易。

var goOn = false,
    counter = 0;

function run() {
    counter++;
    if (goOn) {
        setTimeout(run, 50);
    }
}

function start() {
    counter = 0;
    goOn = true;
    run();
}

function stop() {
    goOn = false;
    console.log(counter);
}
相关问题