【问题标题】:How to make the clearInterval work and why isn't it working?如何使 clearInterval 工作,为什么它不工作?
【发布时间】:2021-07-27 00:04:34
【问题描述】:

我这里有一个条件,如果a = 6,请停止setInterval,所以我使用clearInterval 作为我的条件,但它没有生效,任何人都可以帮助我如何制作clearInterval在那种条件下工作?

请注意,在我的情况下,makig 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);
}

【问题讨论】:

  • a 未在 doSomething 之外定义。
  • 这能回答你的问题吗? What is the scope of variables in JavaScript?
  • @HereticMonkey 不,我知道变量作用域的概念,即使我将if (a = 6) { clearInterval(id); } 放在 doSomething 函数中,它也不起作用,我只是不知道如何使它起作用。跨度>
  • 你必须在间隔回调中调用clearIntervalStop setInterval call in JavaScript
  • 离题 - 在 if 语句中,您分配 (=) 而不是将 (==) 6 与变量 a 进行比较。 6truthy 所以 if 语句将始终执行。

标签: javascript function setinterval clearinterval


【解决方案1】:

您可以在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..');

【讨论】:

  • Thsnks,但我怎样才能让doSomething 在一段时间后执行?
  • 谢谢,但我怎样才能让doSomething 在一段时间后执行?使用 setTimeout(doSomething, 5000) 似乎使 clearInterval 不起作用。
  • @Dorothy 我已经更新了代码示例以解决您希望它在调用doSomething之前等待一段时间的评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 2021-12-27
  • 2016-01-19
  • 2016-11-19
  • 1970-01-01
  • 2018-02-23
相关资源
最近更新 更多