I want to start the timer on the start , which will be in the format MM:SS after an hour format should look like HH:MM:SS. on pause the timer should stop again . User can start/Pause any time the timer should continue from the last time it was paused.
start(){
setInterval(()=>{
let timer = 0;
let minutes = 0 ;
let hour = 0 ;
let seconds = 0;
if(seconds > 3600){ // to increment the hour value
}
if( minutes < 60){ // to calculate minutes
}
concole.log(timer); //to get timer value in format MM:SS and HH:MM:SS
},1000)
}
pauseTimer(){
// need to implement logic
}
Need to implement a logic to get a timer continue/pause. I am getting confused to implement login for start and pause function.
CodePudding user response:
Try with angular by using following code..
- TimerComponent.ts
export class TimerComponent implements OnInit
{
constructor() { }
ngOnInit(): void {
}
timer:string="";
minutes = 0;
hour = 0;
seconds = 0;
setTimer:string="";
isStart:boolean=false;
timerInterval:any;
start()
{
this.isStart=true;
this.timerInterval=setInterval(() => {
if (this.minutes > 59) { // to increment the hour value
this.hour=this.hour 1;
this.seconds=0;
this.minutes=0;
}
if (this.seconds > 59) { // to calculate minutes
this.minutes=this.minutes 1;
this.seconds=0;
}
this.seconds=this.seconds 1;
console.log( this.timer=`${this.hour}:${this.minutes}:${this.seconds}`); //to get timer value in format MM:SS and HH:MM:SS
}, 1000)
}
pauseTimer() {
// need to implement logic
this.isStart=false;
this.setTimer=this.timer;
clearInterval(this.timerInterval);
}
}
- TimerComponent.html
<div >
<div >
<label for="">{{timer}}</label>
</div>
<div >
<div >
<button (click)="start()" [disabled]="isStart">
Start Timer
</button>
<button (click)="pauseTimer()">
Pause Timer
</button>
</div>
</div>
<div >
<label for="">{{setTimer}}</label>
</div>
</div>
CodePudding user response:
This is the simplest way, no formatting included.
timer = 0; // seconds
intervalId = 0;
get hours() {
return Math.floor(this.timer / 3600);
}
get minutes() {
return Math.floor(this.timer / 60) % 60;
}
get seconds() {
return this.timer % 60;
}
start() {
if (!this.intervalId)
this.intervalId = setInterval(() => this.timer , 1000);
}
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = 0;
}
}
<p>{{ hours }}:{{ minutes }}:{{ seconds }}</p>
<button (click)="start()">START</button>
<button (click)="stop()">STOP</button>