How to make countdown timer with RxJS Observables?
I am the take...()
lover, so I am using takeWhile()
as follow ( RxJS 6.x.x, in ES6 way )
import {timer} from 'rxjs';
import {takeWhile, tap} from 'rxjs/operators';
let counter = 10;
timer(1000, 1000) //Initial delay 1 seconds and interval countdown also 1 second
.pipe(
takeWhile( () => counter > 0 ),
tap(() => counter--)
)
.subscribe( () => {
console.log(counter);
} );
Using timer
, scan
and takeWhile
if you don't want to depend on a variable for your starting time, the 3rd argument in scan
is the starting number
timer$ = timer(0, 1000).pipe(
scan(acc => --acc, 120),
takeWhile(x => x >= 0)
);
Check it out on Stackblitz
With interval, allows you to specify how long a second is
const time = 5 // 5 seconds
var timer$ = Rx.Observable.interval(1000) // 1000 = 1 second
timer$
.take(time)
.map((v)=>(time-1)-v) // to reach zero
.subscribe((v)=>console.log('Countdown', v))
You were on the right track - your problem was that timer
does not exist on the prototype (and thereby on Observable.range()
)but on Observable (see the RxJS docs). I.e. jsbin
const start = 10;
Rx.Observable
.timer(100, 100) // timer(firstValueDelay, intervalBetweenValues)
.map(i => start - i)
.take(start + 1)
.subscribe(i => console.log(i));
// or
Rx.Observable
.range(0, start + 1)
.map(i => start - i)
.subscribe(i => console.log(i));