First of all thanks for this post:-
I just started working on ionic. This is fantastic to work with this technology. But today I got stuck when I was try to creating a time countdown.
Scenario 1:- Simple countdown : Initialize inside ionViewDidEnter() works great!
.ts file
> ionViewDidEnter() {
> //Call start timer function
> this.remainingTime = 50;
> this.startTimer();
> }
> startTimer() {
> var counter = setTimeout(() => {
> var time = this.getTimerClock(this.remainingTime);
> console.log(time);
> if (this.remainingTime > 0) {
> this.startTimer();
> this.remainingTime--;
> }
> else {
> clearInterval(counter);
> }
> }, 1000);
> }
getTimerClock(inputSeconds: number) {
var sec_num = parseInt(inputSeconds.toString(), 10);
this.remainingTime = sec_num; //Define variable
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
var hoursString = '';
var minutesString = '';
var secondsString = '';
hoursString = (hours < 10) ? "0" + hours : hours.toString();
minutesString = (minutes < 10) ? "0" + minutes : minutes.toString();
secondsString = (seconds < 10) ? "0" + seconds : seconds.toString();
return hoursString + ':' + minutesString + ':' + secondsString;
}
Result:-
00:00:50
00:00:49
00:00:48...
Scenario 2:- I want to show in html page on the basis of value so I did:-
HTML inside ngFor I am calling function initTimer().
<ion-list *ngFor="let post of posts">
<span>{{initTimer(post.remainingSeconds)}}</span>
</ion-list>
In .ts file, I add
//Initialize timer function
initTimer(inputSeconds: number) {
return this.getTimerClock(inputSeconds);
}
Then result is:- (7) 02:48:12âŚ
Now there are two problems:-
- Counter not working:- Looks like initTimer() calling again and again on every change detection.
- Is this good idea to call method inside html page or we have any other better solution?