What's the best way to implement a timer/countdown feature in a component? Is it advisable to use a service for this purpose?
import { Subscription, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';
export class IntervalRunnerOptions {
constructor(
public callback:()=>void,
public period:number=1000,
public initialDelay:number=0,
public TotalTime: number) {
}
}
export class IntervalRunner {
subscription: Subscription = null;
start(options:IntervalRunnerOptions) {
if(this.subscription==null) {
this.subscription = timer(options.initialDelay, options.period).subscribe(result => options.callback());
}
}
stop() {
if(this.subscription!=null) {
this.subscription.unsubscribe();
this.subscription = null;
}
}
}