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;
})
}
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(
...
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With