EasyBB
EasyBB

Reputation: 6574

clear setTimeout inside immediately invoked functions

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

I've learned this was suppose to be better than setInterval though clearing this function does not work. I've tried break as well as return and it keeps looping through the console.log

Any suggestions on how to cancel this function easily?

What I've Tried

        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);
          }

Upvotes: 1

Views: 135

Answers (1)

basilikum
basilikum

Reputation: 10536

clearTimeout (MDN) expects the "timeoutID" and NOT the function as parameter:

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

But when I look closer at your code, it seems that there is another problem:

setTimeout(b,50);

You are calling b without any parameter, so the function parameter bool will always be undefined! Try this:

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

Then it should only iterate once. And then you don't need to clear the timeout at all (you just stop setting new timeouts):

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);
          }
       })();
   }

Now you only have to figure out what your abort condition is and bring that in, at the right place.

EDIT (Answer to your comment)

It seems you just want one function that starts the interval and one function that stops it. So what follows is a minimal example of such a setup (also with counting the iterations). It should be fairly easy to adapt this to your own needs.

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);
}

Upvotes: 5

Related Questions