derrickrozay
derrickrozay

Reputation: 1046

How to destroy/stop observable interval

I have a countdown timer that continues to run after the user has left the page. When the user leaves the page I want to destroy the countdown timer from running or stop it. How can I do this?

countdown.ts

public time: number;
public countDown:Observable<any>;
public currentUnix;

constructor() {
    this.currentUnix = moment().unix();
    this.time = moment(1503773977000).unix() - this.currentUnix;
}


ngOnInit() {
    this.countDown = Observable.interval(1000)
      .map(res => {
        return this.time = this.time - 1
      })
      .map(res => {

        let timeLeft = moment.duration(res, 'seconds');
        let string: string = '';

        // Days.
        if (timeLeft.days() > 0)
          string += timeLeft.days() + ' Days';

        // Hours.
        if (timeLeft.hours() > 0)
          string += ' ' + timeLeft.hours() + ' Hours';

        // Minutes.
        if (timeLeft.minutes() > 0)
          string += ' ' + timeLeft.minutes() + ' Mins';

        // Seconds.
        string += ' ' + timeLeft.seconds();
        console.log("string", string);
        return string;
      })
}

Upvotes: 10

Views: 9264

Answers (2)

Madhu Ranjan
Madhu Ranjan

Reputation: 17894

you must have created a subscrtiption based on your this.countDown, you can destroy it in ngOnDestroy,

Excerpt from documentation,

Put cleanup logic in ngOnDestroy(), the logic that must run before Angular destroys the directive.

....
this.subscription = this.countDown.subscribe(...)
...

public ngOnDestroy() {
    this.subscription.unsubscribe();
}

Upvotes: 1

Aleksandr Petrovskij
Aleksandr Petrovskij

Reputation: 1243

You can use takeUntil operator.

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';

...

private onDestroy$ = new Subject<void>();

ngOnDestroy(): void {
    this.onDestroy$.next();
}

ngOnInit() {
    this.countDown = Observable.interval(1000)
                               .takeUntil(this.onDestroy$) // <----
                               .map(
... 

Upvotes: 14

Related Questions