且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 2可重启计时器

更新时间:2023-11-17 16:35:10

例如,您可以使用 switchMap():

const timerControl$ = new Subject<any>();
const timer$ = timerControl$.switchMap(() => Observable.timer(0, 1000));

timer$.subscribe(i => console.log(i));

// start timer
timerControl$.next();

// re-start timer
timerControl$.next();

这是还可以停止计时器的版本:

Here is the version which can also stop the timer:

const timerControl$ = new Subject<number>();
const timer$ = timerControl$.switchMap(
    period => period ? Observable.timer(0, period) : Observable.empty()
);

timer$.subscribe(i => console.log(i));

// start timer
timerControl$.next(1000);

// re-start timer with different period
timerControl$.next(500);

// stop timer
timerControl$.next(0);