angulartypescriptclearinterval

Interval not getting cleared in angular typescript


Interval is not getting cleared even after passing intervalId in the clearInterval() function. I want the interval (scheduler) to stop after some time. I have multiple intervals running. I want other intervals to stop. Only one interval should run at a time.Where am i doing wrong?

private interval1:any;
private interval2:any;
func1(){

     this.interval1=interval(10000).pipe(startWith(10000)).subscribe(() => {
            console.log("interval1");    
            this.clearAutoRefresh(this.interval2);
          });
}

func2(){

     this.interval2=interval(10000).pipe(startWith(10000)).subscribe(() => {
            console.log("interval2");    
            this.clearAutoRefresh(this.interval1);
          });
}
    
  clearAutoRefresh(intervalIdToClear:any): void {

    if (intervalIdToClear) {
      clearInterval(intervalIdToClear);
    }else{
      console.error("interval not found");
    }
  }

Solution

  • RxJs interval is not the same as setInterval. First one returns a subscription, while the latter returns an interval id.

    For your code, you can try unsubscribing, the subscription returned and stored in interval1 or interval2.

      clearAutoRefresh(intervalIdToClear: Subscription): void {
        if (intervalIdToClear) {
          intervalIdToClear.unsubscribe();
        }else{
          console.error("interval not found");
        }
      }