Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  100] [ 7]  / answers: 1 / hits: 44958  / 7 Years ago, wed, september 20, 2017, 12:00:00

I'm trying to make a countdown timer for my Ionic2 app, the thing is that I was using this method from now countdown timer but now I have to create the countdown like 30:00 min, what's the better way to do it? Time could change, and if I want to fire something when the countdown it's done I only have to be comparing the time if it's 0, right?


More From » angular

 Answers
4

You can 'listen' to the timer and trigger the action when the countdown is 0. And to display the timer, use a pipe.



HTML



{{counter | formatTime}}    


TypeScript



  countDown:Subscription;
counter = 1800;
tick = 1000;
ngOnInit() {
this.countDown = timer(0, this.tick)
.subscribe(() => --this.counter)
}
ngOnDestroy(){
this.countDown=null;
}


Pipe



//for MM:SS format
transform(value: number): string {
const minutes: number = Math.floor(value / 60);
return ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2);
}


DEMO



//for HH:MM:SS format

transform(value: number): string {
const hours: number = Math.floor(value / 3600);
const minutes: number = Math.floor((value % 3600) / 60);
return ('00' + hours).slice(-2) + ':' + ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2);
}


DEMO



If you wish to use a service:



Service



 ...
getCounter(tick) {
return timer(0, tick)
}
...


Component



  countDown;
counter=1800 ;
tick=1000;

constructor(private myService: MyService) {
}

ngOnInit() {
this.countDown = this.myService.getCounter(this.tick).subscribe(() => this.counter--);

}

ngOnDestroy(){
this.countDown=null;
}


Pipe



  ...  
transform(value: number): string {
//MM:SS format
const minutes: number = Math.floor(value / 60);
return ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2);

// for HH:MM:SS
//const hours: number = Math.floor(value / 3600);
//const minutes: number = Math.floor((value % 3600) / 60);
//return ('00' + hours).slice(-2) + ':' + ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2);

}


DEMO


[#56440] Friday, September 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
breap questions
Thu, Jun 24, 21, 00:00, 3 Years ago
Wed, Mar 18, 20, 00:00, 4 Years ago
Mon, Oct 7, 19, 00:00, 5 Years ago
;