开始/暂停计时器单击事件



我想在开始时启动计时器,这将是在格式MM:SS后一个小时的格式应该看起来像HH:MM:SS。在暂停时,计时器应该再次停止。用户可以在任何时间开始/暂停计时器,计时器应该从上次暂停的时间开始继续。

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
}

需要实现一个逻辑来获得一个定时器继续/暂停。我很困惑实现登录的开始和暂停功能。

Try with angular by using following code..
  1. 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 class="container my-5">
    <div class="row ">
    <label for="">{{timer}}</label>
    </div>
    <div class="row my-5">
    <div class="col-md-6">
    <button class="btn btn-primary" (click)="start()" [disabled]="isStart">
    Start Timer
    </button>
    <button class="btn btn-secondary mx-5" (click)="pauseTimer()">
    Pause Timer
    </button>
    </div>
    
    </div>
    <div class="row">
    <label for="">{{setTimer}}</label>
    </div>
    </div>
    

    这是最简单的方法,不包含任何格式。

    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>
    

    最新更新