【问题标题】:Unable to stop setInterval() in angular无法以角度停止 setInterval()
【发布时间】:2019-07-20 15:04:11
【问题描述】:

我在角度使用setInterval() 来刷新我的页面,但页面的刷新并没有停止。我也使用过clearInterval(),但它似乎不起作用。请指导并告诉我代码是否有问题或是否有其他停止刷新的方法。

我在ngOnDistroy 中使用了clearInterval(),因为它会影响其他 组件也是如此。但它也没有奏效。

AppComponent.ts

import { Component } from '@angular/core';
export class AppComponent {
  intervalId;
  i:number=0;
  n:number=0;

  ngOninit(){

  }

  refresh(){
    this.n++;
    alert("**** this is refresh method with "+this.n+" times.****");
    this.intervalId=setInterval(()=>{
      this.i++;
      if(this.i>3){
        console.log("we are in stop method");
        this.stopRefresh();
      }
      this.refresh();
    },60000);
  }

  stopRefresh(){
  clearInterval(this.intervalId);}


}

AppComponent.html

<div class="row">
    <div class="col-xs-12">
      <div>
        <button (click)="refresh()">Test</button>
      </div>
    </div>
</div>

我希望代码在变量 'i' 的值达到 3 后停止,但它会继续运行并且永远不会停止。

【问题讨论】:

  • 我的回复是否回答了您的问题?

标签: angular setinterval


【解决方案1】:

您的代码的问题是,您在递归函数“refresh”中调用“setInterval”,因此每次遇到“setInterval”都会创建一个新实例。

要解决此问题,您可以将 setInterval 逻辑分离到一个新方法中并在 setInterval 中调用它。以下代码将修复它。

  refresh(){
    this.n++;
     console.log("we are in start method");
   // alert("**** this is refresh method with "+this.n+" times.****");

    this.intervalId=setInterval(()=>{

     this.myIntervalCode();
     // this.refresh();
    },3000);
  }

  myIntervalCode(){  
     this.i++;
      console.log("we are in start method");
      if(this.i>3){
        console.log("we are in stop method");
        this.stopRefresh();
      }
  }

  stopRefresh(){
  clearInterval(this.intervalId);
  }

【讨论】:

    【解决方案2】:

    setIterval(callback, 60000) 使回调每 60_000 毫秒调用一次。您的代码会在此时间间隔内调用 this.refresh();,这会为您的刷新再生成一个时间表。所以它将在 60 秒内调用 1 次,在 120 秒内调用 2 次,在 180 秒内调用 4 次等等。删除那条线,一切都应该更好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 2020-03-14
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多