POV
POV

Reputation: 12025

How stop interval timer?

How stop interval when you move to another component in Angular 7:

public s: Observable<any>;

this.s = interval(5000)
      .pipe(takeWhile(() => this.visitors.length > 0))
      .subscribe(() => {});

I tried to stop interval in component destructor:

   ngOnDestroy() {
      this.s.unsubscribe();
  }

Upvotes: 1

Views: 3850

Answers (1)

Nimer Awad
Nimer Awad

Reputation: 4199

You made 2 mistakes; let me describe them:

  • Calling subscribe() function doesn't return Observable; pipereturns.
  • Using unsubscribe won't stop the interval.

I Use setInterval instead of interval like:

timer: any;

ngOnInit() {
    this.timer = setInterval(() => {
        // here do whatever you want every 5 seconds
    }, 5000);
}

And use clearInterval function onDestroy; like:

ngOnDestroy() {
    clearInterval(this.timer);
}

Upvotes: 3

Related Questions