【发布时间】:2018-04-14 11:37:53
【问题描述】:
我正在尝试创建一个倒计时计时器,一旦计时器在 Angular 4 中达到低于 1 分钟(59 秒或更短)的时间用于体育赛事时钟,它将显示精确的毫秒数,但我遇到了 setInterval 函数的问题。代码如下:
JavaScript:
timer: number = 100;
intervalId: number = -1;
start() {
this.intervalId = setInterval(() => {
this.timeIt()
}, 1000);
if (this.timer <= 0) {
this.stop();
}
}
stop() {
clearInterval(this.intervalId);
this.intervalId = -1;
}
startStop() {
if(this.intervalId == -1) {
this.start();
} else {
this.stop();
}
}
timeIt() {
this.timer--;
if (this.timer == 0) {
clearInterval(this.intervalId);
}
}
convertSeconds(s) {
var minutes = Math.floor(s / 60);
var seconds = (s % 60)
var milliseconds = s;
if (this.timer >= 60)
return p5.prototype.nf(minutes, 1) + ':' + p5.prototype.nf(seconds, 2);
else if (this.timer < 10)
return p5.prototype.nf(seconds, 1) + '.';
else
return p5.prototype.nf(seconds, 2) + '.';
}
HTML:
<h1>{{ convertSeconds(timer) }}</h1>
<button (click)="startStop()">Start/Stop</button>
我在使用 setInterval 函数时遇到问题,我知道如果我使用的参数是 1000,我无法计算毫秒数,但是当我尝试使用 1 或 10 作为参数时,代码会出现问题。正如您在 HTML 代码中看到的那样,我正在调用 convertSeconds() 函数,该函数在页面上呈现时间。卡在这个问题上一段时间了,求大神帮忙!
【问题讨论】:
-
setInterval不受信任。使用new Date()会准确设置计时器。
标签: javascript angular timer