Home > Back-end >  How to make 5 minute countdown timer with RxJS and angular
How to make 5 minute countdown timer with RxJS and angular

Time:12-11

The countdown should go from 4:59,4:58,....0:00.I am new to RxJS and angular. I found examples online which countdown from certain date, but I just want a 5 minute countdown. I tried this:

export class CounterComponent {
  @Input() since!: number
  readonly timeToShow$ = timer(0, 1000).pipe(
    map(() => Math.floor((Date.now() / 1000 - this.since) / 60)),
  )
}
<span *ngIf="((timeToShow$ | async) || 0) > 0; else recentlyAdded">
    {{ timeToShow$ | async }} Minute{{ (timeToShow$ | async) === 1 ? '' : 's' }}
  </span>

But this gives me elapsed time from today's date. I just need a 5 minute countdown.

CodePudding user response:

To create an observable that emits decreasing integers every second for 300 seconds, you can do something like this:

  secondsRemaining$ = timer(0, 1000).pipe(
    map(n => 300 - n),
    takeWhile(n => n >= 0),
  );

  // emits: 300, 299, 298 ... 0

timer - emits increasing integers at the specified interval

map - is used to reverse the increasing number into the time remaining

takeWhile - completes the observable when the condition is met


If we use milliseconds, instead of seconds, we can use Angular's date pipe to nicely format the time:

<p> 
  {{ timeRemaining$ | async | date:'mm:ss' }}      <!-- ex: 03:47 -->
</p>

To put it into a component that takes the duration as an @Input(), it could look something like this:

export class CountDownComponent {

  @Input() seconds = 300;

  timeRemaining$ = timer(0, 1000).pipe(
    map(n => (this.seconds - n) * 1000),
    takeWhile(n => n >= 0),
  );

}

Here's a working StackBlitz demo.

  • Related