TheClassyCoder
TheClassyCoder

Reputation: 103

How to make the clearInterval work and why isn't it working?

I have a condition here which is if a = 6, stop the setInterval so I used clearInterval for my condition, but it doesn't take effect, anybody can help me how I can make the clearInterval work under that condition?

Please take note that in my case makig doSomething to execute after some amount of time is of paramount importance as well, that's why I used setTimeout here.

function doSomething() {

  let a = 1;

  return setInterval(() => {
    if (a < 6) {
      a++;
      console.log(a);
    } else {
      a = 1;
    }
  }, 1000)
}

setTimeout(doSomething, 5000);

var id = doSomething();

if (a === 6) {
  clearInterval(id);
}

Upvotes: 0

Views: 72

Answers (1)

Tom O.
Tom O.

Reputation: 5941

You can call clearInterval inside the setInterval - I think this is what you're trying to achieve:

let intervalId;

function doSomething() {
  let a = 1;

  return setInterval(() => {
    console.log(a);

    if (a++ === 6) {
      clearInterval(intervalId);
    }
  }, 1000);
}

setTimeout(() => {
  intervalId = doSomething();
}, 5000);

console.log('Waiting for 5 seconds before calling doSomething..');

Upvotes: 1

Related Questions