I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked.
For example: 21(min):02(sec)
What I am struggling with is updating the minutes and seconds in real-time when they change. I am not sure how to achieve this functionality.
Please see my code snippet below:
startTime = false;
minutes: number;
seconds: number;
getTime() {
this.startTime = !this.startTime;
this.runTime();
setInterval(this.runTime, 1000);
}
runTime() {
this.todayDate = new Date();
this.minutes = this.todayDate.getMinutes();
console.log(this.minutes) /* here I can see in console that it prints minutes and seconds in real
time, but in the UI nothing happens, it appears only the date when I
click the button */
this.seconds = this.todayDate.getSeconds();
}
In my HTML file:
<button type="button" class="btn btn-primary" (click)="getTime()">Time</button>
<div *ngIf="startTime">
Time: {{minutes}} : {{seconds}}
</div>
If anyone could provide guidance on how to update the timer in real-time, I would greatly appreciate it.