How to do a timer in Angular 5

Samuel picture Samuel · May 21, 2018 · Viewed 110.3k times · Source

I'm using Angular 5.

I want to know how can I start timing when a 'play' button is pressed, in order to know how much time has passed since I clicked.

I'd also like to know if it's possible to stop the timer and then be able to continue with the same time before.

I've finally solved my question with Pardeep Jain answer. Athough it wasn't exactly what I was looking for. I didn't want a countdown, I wanted to count the duration. Here is the code I've used at the end:

time: number = 0;
interval;

startTimer() {
  this.play = true;
  this.interval = setInterval(() => {
    this.time++;
  },1000)
}

pauseTimer() {
  this.play = false;
  clearInterval(this.interval);
}

Answer

Pardeep Jain picture Pardeep Jain · May 21, 2018

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here