如何使 clearInterval 起作用,为什么不起作用?

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

我这里有一个条件,如果a = 6,停止setInterval所以我用clearInterval来满足我的条件,但是它没有生效,任何人都可以帮助我我怎样才能让 clearInterval 在这种情况下工作?

请注意,在我的例子中,让 doSomething 在一段时间后执行也是最重要的,这就是我在这里使用 setTimeout 的原因。

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

您可以在 setInterval 中调用 clearInterval - 我认为这就是您要实现的目标:

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..');