clearInterval() 在 Angular 5 个应用程序中不起作用

clearInterval() not working in Angular 5 app

setInterval() 对我来说工作正常并且计时器启动,但是当计数器值达到 100 时 clearInterval() 不会停止计时器。它连续 运行。任何帮助表示赞赏。

下面是我的组件代码 -

export class AppComponent {
  counter=0;
  progressInterval;

  ngOnInit(){
    this.progressInterval=setInterval(()=>{
      this.counter=this.counter+10;
      if(this.counter>=100){        
          clearInterval(this.progressInterval);
      }
    },200);
  }
}

下面是我的组件 HTML 代码 -

<p style="margin:20px;">
    <ngb-progressbar
      type="warning"
      [value]="counter"
      [striped]="true"
      [animated]="true"
    >{{counter}}</ngb-progressbar>
  </p>

这是显示进度条的屏幕截图 -

Screenshot

谢谢

或者您可以将间隔分配给变量。让我们这样说:

ngOnInit() {
    const int = setInterval( () => {
      this.counter += 10;
      if ( this.counter >= 100 ){        
          clearInterval( int );
      }
    }, 200);
  }

已使用 ES6 模块进行测试(尝试使用 chrome 61 及更高版本

<script type="module">
  class AppComponent {
    constructor() {
      this.counter = 0;
      this.progressInterval;
    }

    ngOnInit() {
      this.progressInterval = setInterval(() => {
        this.counter += 10;
        console.log('this.counter', this.counter);

        if(this.counter >= 100){
          clearInterval(this.progressInterval);
          console.log('cleaned and finished');
        }
      },200);
    }
  }

  const instance = new AppComponent();
  
  instance.ngOnInit();
</script>

您使用 ES6 语法的代码可以完美运行。 似乎 Angular5 有另一种行为检查这个答案:

问题已为我解决。我忘了从 "timers" 模块导入 "clearInterval"。现在我像下面这样更新了,现在可以用了。

import { 
  setInterval,
  clearInterval
} from 'timers';

感谢大家在这方面的帮助。

谢谢

这是因为此变量范围仅限于当前函数。 和区间函数有它自己的这个变量,所以它无法检测到 this.progressInterval 变量。

尝试使用这种方式:

ngOnInit(){

    const initScope = this;
    this.progressInterval=setInterval(()=>{
      initScope.counter=initScope.counter+10;
      if(initScope.counter>=100){        
          clearInterval(initScope.progressInterval);
      }
    },200);
  }

Angular 中的任何 Interval 实现都需要考虑几件事:

  1. 确保只实例化一次。在此示例中,如果您要在清除计数器之前离开组件和 return,它将创建第二个实例,而原始实例继续运行。

  2. 在使用 OnDestroy 离开页面或组件范围时对间隔进行故障安全清除。您总是需要 clear/dispose 完成后的间隔。

import { Component, OnInit, OnDestroy } from '@angular/core';

[..]

export class YourComponent implements OnInit, OnDestroy {

  progressInterval: any;

  ngOnInit() {
    [..]
  }

  ngOnDestroy() {
    if (this.progressInterval) { clearInterval(this.progressInterval); }
  }

}