【问题标题】:Why isn't setInterval clearing?为什么 setInterval 不清除?
【发布时间】:2021-12-29 01:51:18
【问题描述】:

为什么stopInterval 不清除mavemave 继续记录 'g' 即使在调用 stopInterval() 之后。

let boy = 'bama';
let count = 1;

const name = () => {
  let stopInterval = () => {
    if (count >= 1) {
      clearInterval(mave);
    }
  }

  if (boy === 'lama') {
    stopInterval();
    var move = setInterval(() => {
      console.log('u');
    },3000);
  } else if (boy === 'bama') {
    stopInterval();
    var mave = setInterval(() => {
      console.log('g');
    },3000);
  }
};

name();

【问题讨论】:

  • 您在拨打setInterval 之前先拨打stopInterval,所以我不知道您期望会发生什么。 ???

标签: javascript setinterval


【解决方案1】:

setInterval 调用时将返回timerId,您必须清除该 ID。

您没有在每次间隔运行时清除id,您可以在每次运行您传递给setInterval的回调时调用函数stopInterval

let boy = "bama";
let count = 1;

const name = () => {
  let id;                          //change - create id variable on top of function
  let stopInterval = () => {
    if (count >= 1) {
      clearInterval(id);
    }
  };

  if (boy === "lama") {
    id = setInterval(() => {       //change - Assigning ID
      stopInterval();              //change - Run every time and check
      console.log("u");
    }, 3000);
  } else if (boy === "bama") {
    id = setInterval(() => {       //change - Assigning ID
      stopInterval();              //change - Run every time and check
      console.log("g");
    }, 3000);
  }
};

name();

Alternate short solution

let boy = "bama";
let count = 1;

const name = () => {
  var timerId = setInterval(() => {
    if (count++ >= 3) clearInterval(timerId);
    if (boy === "lama") console.log("u");
    else console.log("g");
  }, 3000);
};

name();

【讨论】:

  • 成功了,非常感谢!
【解决方案2】:

这个程序似乎缺少一些东西,唯一设置的间隔是

var mave = setInterval(()//etc

将“mave”设置为仅在该 if 语句的范围内可见的局部变量,之后就没有“stopInterval”,您只需在启动它之前调用它

首先,您需要使 mave 成为一个全局变量,或者只是将其作为参数传递给 stopInterval (但它会是相同的,所以不妨使用它)但主要是,您实际上必须启动后停止它

尝试只制作一个按钮,在点击时清除它,或者任何东西

【讨论】:

    【解决方案3】:

    您没有提供任何条件来停止/清除该间隔。 从一开始,你要做的第一件事就是停止间隔(它还没有开始)。 然后你开始间隔并且不提供任何东西来阻止它。 在 console.log("g") 的位置设置 stopIntervall 命令,在调试时您会看到差异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      • 2016-03-14
      • 2016-02-09
      相关资源
      最近更新 更多