停止Angular2 CountDown

时间:2017-12-14 11:48:11

标签: angular timer countdown

我想停止我的Countdown,但它不会停止并且仍在运行我有这个:

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();
            }
        });

当计时器等于0时,它会变为-10,等等......

还有另一种方法可以阻止该计时器吗?

2 个答案:

答案 0 :(得分:2)

您没有取消订阅正确的变量。这是你应该怎么做:

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

答案 1 :(得分:1)

我最终创建了一个名为stopTimer()的函数:

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

它会停止Timer并停止CountDown