Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a stopwatch in angular 6

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.

allUserTaskArr = [
    {
      'name': 'abc',
     'id':1,
     'start': true,
     'end': false
    },
     {
      'name': 'xyz',
     'id':1,
     'start': true,
     'end': false
    }

  ];
 
 startTask (item) {
    if(item.start) {
      item.end =  true;
      item.start= false;
    } 
  }

  EndTask (item) {
    if(item.end) {
      item.end =  false;
      item.start= true;
    }
  }
<div class="row no-gutters">
  <div class="card width hr" *ngFor="let item of allUserTaskArr">
    <div class="card-header">
      {{item.due | date}}
    </div>
    <div class="card-body pad-125">
      <div class="row no-gutters">
        <div class="col-md-12">
          {{item.name}}
          <div class="float-right">
            <button class="btn btn-info mar-l-r-0-5" *ngIf="item.start" (click)="startTask(item)">Start Timer</button>
            <button class="btn btn-danger mar-l-r-0-5" *ngIf="item.end" (click)="EndTask(item)">End Timer</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
like image 345
lakhan Avatar asked Apr 26 '26 12:04

lakhan


2 Answers

Create a timer which grows per sec, then convert the time to display format

   timer(0, 1000).subscribe(ec => {
          this.time++;
          this.timerDisplay = this.getDisplayTimer(this.time);
        });

getDisplayTimer(time: number) {
    const hours = '0' + Math.floor(time / 3600);
    const minutes = '0' + Math.floor(time % 3600 / 60);
    const seconds = '0' + Math.floor(time % 3600 % 60);

    return {
      hours: { digit1: hours.slice(-2, -1), digit2: hours.slice(-1) },
      minutes: { digit1: minutes.slice(-2, -1), digit2: minutes.slice(-1) },
      seconds: { digit1: seconds.slice(-2, -1), digit2: seconds.slice(-1) },
    };
  }`
like image 86
Shekhar Avatar answered Apr 28 '26 01:04

Shekhar


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>
like image 23
MoxxiManagarm Avatar answered Apr 28 '26 03:04

MoxxiManagarm