Timer countdown Angular 2

StuartDTO picture StuartDTO · Sep 20, 2017 · Viewed 20.8k times · Source

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?

Answer

Double Expresso picture Double Expresso · Sep 20, 2017

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