Search code examples
javascriptangularrxjscountdowntimer

rxjs 6 countdown timer subscribe angular 6


I try to implement a countdown timer in angular 6 using rxjs 6. I also need to be able to subscribe to results and to reset the timer:

What I tried:

var timer =  interval(1000).pipe(
take(4)
);
timer.subscribe(x => console.log(x));

Result:

0
1
2
3

What I need is to reverse the timer to count from 3 to 1

I found this coundown function to implement reverse count, but I cannot subscribe to it, like in first example

 interval(1000).pipe(
 map((x) => { console.log( x) })
  );

Result:

empty


Solution

  • You can use timer instead of interval, to actually implement the countdown you should map the timer result like this: map(i => countdownStart - i)

      const countdownStart = 3;
    
      Rx.Observable
        .timer(1000, 1000)
        .map(i =>  countdownStart - i)
        .take(countdownStart + 1)
        .subscribe(i => console.log(i));
    

    Logs: 3 2 1 0

    Another possible solution is to use the range operator.

    Rx.Observable
      .range(0, countdownStart + 1)
      .map(i => countdownStart - i)
      .subscribe(i => console.log(i));
    

    Logs: 3 2 1 0