角停止和清除间隔

时间:2019-06-30 18:17:58

标签: angular angular7 angular8

我在组件中拥有这个:

  ngOnInit() {
    setInterval(() => {
        console.log('still running...');
      }, 1000);
    }

  stop() {
    clearInterval();
  }

如何使其停止并清除,以便不再在控制台中看到任何console.logs?

3 个答案:

答案 0 :(得分:1)

您应该存储从setInterval返回的引用,并将其作为参数传递给clearInterval

  intervalRef;

  ngOnInit() {
    this.intervalRef = setInterval(() => {
      console.log('still running...');
    }, 1000);
  }

  stop() {
    clearInterval(this.intervalRef);
  }

您可以尝试here

答案 1 :(得分:1)

您需要提供要清除的时间间隔的ID:

intervalID;

ngOnInit() {
  this.intervalID = setInterval(() => {
    console.log('still running...');
  }, 1000);
}

stop() {
  clearInterval(intervalID);
}

答案 2 :(得分:1)

保持对间隔的引用,然后可以清除它

interval: any;

ngOnInit() {
   this.interval = setInterval(() => {
       console.log('still running...');
      }, 1000);
    }

  stop() {
    clearInterval(this.interval);
  }