首页 > 解决方案 > 在 Angular 6 中使用 clearInterval() 停止刷新功能不起作用?

问题描述

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

  1. 单击刷新按钮时刷新页面(直接向前)

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

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

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()to calrefresh()方法,如下所示:

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>

这是现在的行为,在我从 DDL 中clearInterval()选择后不起作用。 1.步骤 1 2.步骤 2 3.步骤 3Cancel



感谢您的帮助。

编辑:这是它的SlackBitz

标签: typescriptangular6clearinterval

解决方案


计时器可能会有所帮助,但因狂奔而臭名昭著,因此请谨慎使用。只要您确保创建的计时器不会超出您的需要,并且您不会忘记现有的计时器,就可以了。像这样的东西:

保存对计时器的引用

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);
    }
}

推荐阅读