-->

Stop Angular2 CountDown

2019-05-21 04:19发布

问题:

I'd like to stop my Countdown but it does not stops and still running I have this :

import { Subscription } from 'rxjs/Subscription';

sub: Subscription;
countDown;
count;
this.count = 100;
this.countDown = Observable.timer(0, 1000)
        .take(this.count)
        .map(() => this.count = this.count-10);

this.sub = Observable.interval(1000)
        .subscribe((val) => {
            if(this.count===0){
                this.sub.unsubscribe();
            }
        });

and when the timer equals to 0 it goes to -10, etc...

Is there another way to stop that timer?

回答1:

You didn't unsubscribe to the right variable. Here is how you should do :

this.count = 100;
this.countDown = Observable.timer(0, 1000)
  .subscribe(x => {
      this.count = this.count - 10;
  });

this.sub = Observable.interval(500)
  .subscribe(x => {
     console.log(this.count);
     if (this.count === 0) {
        this.countDown.unsubscribe();
     }
});

Here is a StackBlitz example



回答2:

I ended up creating a function called stopTimer() that is :

stopTimer(){
        this.countDown = null;
        this.sub.unsubscribe();
}

It will stop the Timer and will stop the CountDown.