[Solved] count down timer function in angularJS 2


You could do it like this:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button (click)="buttonClicked()">{{ started ? 'reset' : 'start' }}</button>
      <br />
      <span>{{ time.getHours() }}</span>:
      <span>{{ time.getMinutes() }}</span>:
      <span>{{ time.getSeconds() }}</span>
    </div>
  `,
})
export class App {
  name:string;
  started = false;
  time = new Date(2000, 1, 1, 1, 0, 0);

  constructor() {
    this.name="Angular2"

    this._timerTick();
  }

  private _timerTick() {
    if (this.started) {
      this.time.setSeconds(this.time.getSeconds(), -1);
    }

    setTimeout(() => this._timerTick(), 1000);
  }

  buttonClicked() {
    if (this.started) this.reset();
    else this.start();
  }

  start() {
    this.started = true;
  }

  reset() {
    this.started = false;
    this.time = new Date(2000, 1, 1, 1, 0, 0);
  }
}

live demo: https://plnkr.co/edit/BkMkAuSoqVgQMhqEKAAg?p=preview

But there are, like always, multiple ways to achieve the goal! 🙂

1

solved count down timer function in angularJS 2