无法重置setInterval

时间:2019-06-12 15:29:25

标签: angular setinterval

我无法在ts中重置setInterval函数。我已经尝试了clearInterval,但只是停止了间隔。我也尝试将其设置为undefined但没有帮助。用例基本上是找到两个websocket输入之间的时间间隔,并检查是否小于两分钟。但是最终发生的是计时器保持了更快的速度。

function {
  this.timeLeftForPlantThree = 120;

  const a = 1000;
  let interval3;
  clearInterval(interval3);
  interval3 = undefined;
  if (typeof(interval3) === 'undefined') {
    interval3 = setInterval(() => {
      if (this.timeLeftForPlantThree > 0) {
        this.timeLeftForPlantThree--;
        this.plantThreeRed = false;
        console.log(this.timeLeftForPlantThree);
      } else {
        console.log('***' + this.timeLeftForPlantThree);
        this.plantThreeRed = true;
      }
    }, a);
  }
}

2 个答案:

答案 0 :(得分:0)

将时间间隔分配给变量,然后将其重置:

this.interval = setInterval(() => {
      // do something here
}, 1000);

并重置:

if (this.interval) clearInterval(this.interval);
this.interval = null;

关于代码,您正在创建空变量/时间间隔,然后清除该变量/时间间隔会引发错误。

并在全局范围内声明变量。

let interval3;

并在函数中运行它:

function runInterval() {
  this.timeLeftForPlantThree = 120;

  const a = 1000;
  if (!this.interval3) {

    this.interval3 = setInterval(() => {
      if (this.timeLeftForPlantThree > 0) {
        this.timeLeftForPlantThree--;
        this.plantThreeRed = false;
        console.log(this.timeLeftForPlantThree);
      } else {
        console.log('***' + this.timeLeftForPlantThree);
        this.plantThreeRed = true;
      }
    }, a);
  }
}

然后将其重置:

function resetInterval() {
  if (this.interval) clearInterval(this.interval);
  this.interval = null;
}

答案 1 :(得分:0)

在这段时间里,您正在做些奇怪的事情!

var interval3 = setInterval(() => {});

function {
  this.timeLeftForPlantThree = 120;
  const a = 1000;
  interval3 = setInterval(() => {

    // call clear interval here when some condition is satisfied

    if (this.timeLeftForPlantThree > 0) {
      this.timeLeftForPlantThree--;
      this.plantThreeRed = false;
      console.log(this.timeLeftForPlantThree);
    } else {
      console.log('***' + this.timeLeftForPlantThree);
      this.plantThreeRed = true;
    }
  }, a);
}