Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.But this gives me elapsed time from today's date. I just need a 5 minute countdown.

What I have tried:

export class CounterComponent {
  @Input() since!: number
  readonly timeToShow$ = timer(0, 1000).pipe(
    map(() => Math.floor((Date.now() / 1000 - this.since) / 60)),
  )
}

<span>
    {{ timeToShow$ | async }} Minute{{ (timeToShow$ | async) === 1 ? '' : 's' }}
  </span>
Posted
Updated 9-Dec-22 8:54am

1 solution

To create a countdown timer that counts down from a specific duration (in this case, 5 minutes), you can use the timer operator in a similar way as before, but instead of using the current time to calculate the remaining time, you can use the total duration of the countdown to calculate the remaining time.

Here is an example of how you can do this:

import { timer } from 'rxjs';

const countdown$ = timer(0, 1000).pipe(
  take(300),
  map(secondsElapsed => 300 - secondsElapsed)
);

countdown$.subscribe(secondsLeft => {
  this.secondsLeft = secondsLeft;
});


In this example, we use the timer operator to create an observable that emits an event every second, and we use the take operator to limit the observable to 300 events (5 minutes).

We then use the map operator to transform the emitted values so that they represent the number of seconds remaining in the countdown. To do this, we subtract the number of seconds that have elapsed from the total duration of the countdown (300 seconds).

Finally, we subscribe to the observable and use the values emitted by the timer to update the UI of our Angular component. In the component's template, we can display the remaining time using the secondsLeft property, which is updated with each event emitted by the timer.

<p>{{ secondsLeft }} seconds remaining</p>


I hope this helps!
 
Share this answer
 
Comments
magicfarm 22-Dec-22 9:33am    
The input value should not be defaulted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900