在 Angular 6 中使用 clearInterval() 停止刷新功能不起作用?

Stopping Refresh Functionality Using clearInterval() in Angular 6 is not working?

我在用户有两个选项的页面上实现刷新功能。 Refresh Buttons

  1. 单击“刷新”按钮时刷新页面(直接)

  2. 为用户提供设置刷新频率的选项(在特定时间间隔后刷新页面的选项) Set Interval Refresh

正如您在图像中看到的那样,我存储在以下对象中的每个间隔都有不同的值。

timer: RefreshTimer[] = [
{value: 15000, time: '15 Sec'},
{value: 30000, time: '30 Sec'},
{value: 45000, time: '45 Sec'},
{value: 100000, time: '1 min'},
{value: null, time: 'Cancel'}];

我正在使用 setInterval() 来计算 refresh() 方法,如下所示:

refresh() {
this.router.navigateByUrl('./views/refresh/', { skipLocationChange: true }).then(() => {
  console.log(decodeURI(this.location.path()));
  this.router.navigate([decodeURI(this.location.path())]);
});}

refreshFrequency(time) {
     if(time === null){
        this.counter = 110;
     }
this.progressInterval = setInterval(() => {
  this.counter += 10;
  this.refresh();
  console.log('this.counter', this.counter);

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

}

像这样调用setInterval()

<mat-form-field class="timer" style="width: 10px;">
           <i class="far fa-clock"></i>
           <mat-select class="alarm-dropdown" trigger="alarmTrigger" #alarmSelect>
           <mat-option   *ngFor="let time of timer" 
                  (click)="refreshFrequency(time.value)" 
                  [value]="time.value">
              {{time.time}}
            </mat-option>
            </mat-select>
 </mat-form-field>

这是现在的行为,clearInterval() 在我从 DDL select Cancel 之后不工作。
1. Step 1
2. Step 2
3. Step 3

感谢您的帮助。

编辑:这是它的 SlackBitz

计时器可能会有帮助,但因 运行 疯狂而臭名昭著,因此请谨慎使用。只要您确保您创建的计时器不会超过您的需要,并且您不会丢失对现有计时器的跟踪,您就可以了。 像这样:

保存您对计时器的引用

this.intervalReference = null;

隔离启动和清理计时器的逻辑。确保它只执行一个计时器,否则您的参考将被覆盖。

refreshFrequency(time) {
    if (!this.intervalReference && time !== null) {
        console.log('Creating a timer. It will run every ' + (time / 1000) +  ' seconds');
        this.intervalReference = setInterval(() => {
            this.counter += 10;
            this.refresh();
            console.log('this.counter', this.counter);
            if (this.counter >= 100) {
                clearInterval(this.intervalReference);
                console.log('Timer stopped as expected');
                this.intervalReference = null;
            }
        }, time);
    } else if (time === null && this.intervalReference) {
        console.log('Stopping timer early.');
        clearInterval(this.intervalReference);
    }
}