create a stopwatch in angular 6

lakhan picture lakhan · Mar 4, 2019 · Viewed 7.6k times · Source

I am using angular. I want to implement stopwatch. I have a list which consists of one or more objects. I have a start timer and end the timer button for each item. when I click on the start button this should start the timer for the specific item & when I click on the end timer button this should pause the timer so that I can restart the time. but only one timer should run at a time. if Item A timer is started & if click on the start timer button of Item B it should pause the previous timer & start the new timer for Item B.

Answer

MoxxiManagarm picture MoxxiManagarm · Mar 4, 2019

You will need to create a timer, which is an Observable you can subscribe to. In the callback do the action. For example:

in Component:

import { timer } from "rxjs";

ngOnInit() {
    timer(0, 1000).subscribe(ellapsedCycles => {
      if(this.isRunning) {
        this.time--;
      }
    });
  }

toggleTimer() {
    this.isRunning = !this.isRunning;
  }

and in Template:

<button (click)="toggleTimer()">Toggle timer</button>
<div>{{ time }}</div>