我正在尝试创建一个计时器来从 0 开始计算时间。
但是,当我单击按钮时,时间不计算在内,有谁知道为什么?
如何以这种格式获取此计时器 {{hours}}: {{mminutes}}: {{sseconds}}?
谢谢!
我的代码
Stackblitz
组件.ts
time: number = 0;
interval;
startTimer() {
this.interval = setInterval(() => {
if(this.time = 0) {
this.time++;
} else {
this.time= 0;
}
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}
最佳答案
你喜欢这个日期:'mm:ss' 在 html 中
组件
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
time: number = 0;
display ;
interval;
startTimer() {
console.log("=====>");
this.interval = setInterval(() => {
if (this.time === 0) {
this.time++;
} else {
this.time++;
}
this.display=this.transform( this.time)
}, 1000);
}
transform(value: number): string {
const minutes: number = Math.floor(value / 60);
return minutes + ':' + (value - minutes * 60);
}
pauseTimer() {
clearInterval(this.interval);
}
}
HTML:
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p>{{display }} Seconds</p>
编辑:
'mm:ss'
transform(value: number): string {
const minutes: number = Math.floor(value / 60);
return minutes + ':' + (value - minutes * 60);
}
{HH:MM:SS} 格式
transform(value: number): string {
var sec_num = value;
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = 0;}
if (minutes < 10) {minutes = 0;}
if (seconds < 10) {seconds = 0;}
return hours+':'+minutes+':'+seconds;
}
关于Angular Timer 来计算时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914756/