【问题标题】:Recursive function called in setTimeout is executing even after navigated to other Angular components即使在导航到其他 Angular 组件之后,在 setTimeout 中调用的递归函数仍在执行
【发布时间】:2021-03-28 03:26:08
【问题描述】:

即使在导航到不同的组件之后,停止执行用于显示进度条的递归函数对我来说也变得很有挑战性。

animateProgress() {
    var counter = this.incrementCounter;    //initial value = 0
    if (counter <= 100) {
      this.updateProgressBar(counter);
      setTimeout(()=>{  
        this.animateProgress();   
      }, 3000);
      this.incrementCounter++;
    }
    else {
      return false;
    }
  }
  
updateProgressBar(percentage) {
    $('.progressBarDiv').css("width", percentage + "%");
}

【问题讨论】:

  • 是的,你从来没有在任何地方打电话给clearTimeout,所以它当然会继续运行?
  • 我认为如果你发布整个课程会很有帮助,包括你打电话给animateProgress()的地方

标签: javascript recursion ecmascript-6 angular6 settimeout


【解决方案1】:

我认为您应该使用setInterval,因为您希望该部分代码重复多次。

animateProgress() {
    // removed the local variable counter cause it wasn't really necessary

    // setInterval returns an id that you can later use to cancel the interval
    const interval = setInterval(() => {
        if (this.incrementCounter <= 100) {
          this.updateProgressBar();
          this.incrementCounter++;
        }
        else {
            // when you reach the condition you clear the inverval
          clearInterval(interval);
        }
    }, 3000);
}

updateProgressBar() {
    $('.progressBarDiv').css("width", this.incrementCounter + "%");
}

否则,如果您希望坚持使用 setTimeout 和递归,这将起作用:

animateProgress() {
    if (this.incrementCounter <= 100) {
      this.updateProgressBar();
      this.incrementCounter++;
      setTimeout(()=>{  
        this.animateProgress();   
      }, 3000);
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2016-10-30
    • 2022-01-07
    • 2012-09-10
    • 1970-01-01
    相关资源
    最近更新 更多