You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用setInterval()让函数执行指定次数后停止,解决死循环问题

问题根因
  • setInterval 属于异步执行API,计数器的递增、终止判断逻辑全部写在了setInterval回调函数之外,这部分逻辑只会在调用function_with_interval方法时执行1次,不会跟随定时器的周期触发重复运行
  • 定时器内部回调仅执行了计数器打印和getData()调用,没有任何更新计数器、判断终止条件的逻辑,因此计数器只会从1增加到2后就不再变化,定时器永远无法被清除,形成无限循环
修正方案

将计数器更新、终止判断的逻辑全部移入setInterval的回调函数内部,同时补充组件销毁时的定时器清理逻辑避免内存泄漏,修正后代码如下:

export class AppComponent implements OnInit, OnDestroy  {
  name = 'Angular ' + VERSION.major;
  intervalcounter: number = 1;
  intervalsDef?: number;

  ngOnInit(){
    this.function_with_interval();
  }

  function_with_interval(){
    this.intervalsDef = window.setInterval(()=> {
      console.log(this.intervalcounter);
      this.getData();
      
      if(this.intervalcounter === 40){
        console.log('计数器达到40,停止定时器');
        this.clearTimer();
        return;
      }
      this.intervalcounter++;
    },10);
  }

  getData(){
    console.log("hello")
  }

  private clearTimer() {
    if (this.intervalsDef) {
      clearInterval(this.intervalsDef);
      this.intervalsDef = undefined;
    }
  }

  // 组件销毁时自动清理定时器
  ngOnDestroy() {
    this.clearTimer();
  }
}

内容的提问来源于stack exchange,提问作者Santhosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:06:05