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?
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
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
Try this for timer:
<h5><span id="time" class="text-primary">00:00</span></h5>
component.ts
import { Component, OnInit, ElementRef, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
export class AppComponent implements OnInit {
constructor(private elementRef: ElementRef) { }
ngOnInit() {
var callDuration = this.elementRef.nativeElement.querySelector('#time');
this.startTimer(callDuration);
}
startTimer(display) {
var timer = 1800;
var minutes;
var seconds;
Observable.interval(1000).subscribe(x => {
minutes = Math.floor(timer / 60);
seconds = Math.floor(timer % 60);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
--timer;
if (timer < 0) {
console.log('timer is ended');
}
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With