How to make a countdown timer using RxJS Observables?

I am trying to create a countdown timer using Observables, the examples http://reactivex.io/documentation/operators/timer.html do not seem to work. In this specific example, the timerInterval-related error is not an Observable function returned from the timer.

I also experimented with other approaches, and the best I came up with is:

Observable.interval(1000).take(10).subscribe(x => console.log(x)); 

The problem here is that it counts from 0 to 10, and I want a countdown timer, for example. 10.9.8 ... 0.

I also tried this, but timer does not exist for type Observable

 Observable.range(10, 0).timer(1000).subscribe(x => console.log(x)); 

And also, which does not produce any conclusion.

 Observable.range(10, 0).debounceTime(1000).subscribe(x => console.log(x)); 

To clarify, I need help implementing ReactiveX RxJS, not the MircoSoft version.

+14
reactive-programming observable rxjs
source share
3 answers

You were on the right track - your problem was that timer does not exist on the prototype (and thus on Observable.range() ), but on Observable (see RxJS docs ). That is 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)); 
+23
source share

At intervals, allows you to specify how many seconds

 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)) 
+1
source share

I am a fan of take...() , so I use takeWhile() as follows (RxJS 6.xx, ES6-like)

 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); } ); 
0
source share

All Articles