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>
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) },
};
}`
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With