我正在尝试使用 setInterval 显示一个每秒上升的计时器。
不过,该变量似乎在每个循环中都会自行重置;结果是 HTML 页面上的显示不会改变。
我已将变量移到函数之外,但这不起作用。不太确定从这里去哪里。
this.intervalFour = setInterval(() => this.totalTime(this.secs, this.restSecs), 1000);
totalTime(seconds, rests) {
var fullTime = seconds * 8 + rests * 7;
fullTime--;
var secCounter: any = 0;
var minCounter: any = 0;
secCounter++;
if (secCounter < 10) {
secCounter = "0" + secCounter;
}
if (minCounter < 10) {
minCounter = "0" + minCounter;
}
if (secCounter == 60) {
secCounter = 0;
minCounter++;
}
if (fullTime = 0) {
clearInterval(this.intervalFour);
}
this.m.innerHTML = minCounter;
this.s.innerHTML = secCounter;
console.log(secCounter, minCounter, "test");
}
我知道这是一件很愚蠢的事情,但我找不到让 secCounter 在每个循环中增加 1 的解决方案。
您可以尝试以下方法。
虽然我没有确定的价值,因此我评论了该代码,但您可以根据需要取消注释该代码:
<script type="text/javascript">
var secs = 10;
var restSecs = 10;
var secCounter = 0;
var minCounter = 0;
this.intervalFour = setInterval(() => this.totalTime(this.secs, this.restSecs), 1000);
function totalTime(seconds, rests) {
var fullTime = seconds * 8 + rests * 7;
fullTime--;
this.secCounter++;
if (this.secCounter < 10) {
this.secCounter = "0" + this.secCounter;
}
if (this.minCounter < 10) {
this.minCounter = "0" + this.minCounter;
}
if (this.secCounter == 60) {
this.secCounter = 0;
this.minCounter++;
}
// if (fullTime = 0) {
// clearInterval(this.intervalFour);
// }
console.log("this.minCounter" , this.minCounter);
console.log("this.secCounter" , this.secCounter);
// this.m.innerHTML = this.minCounter;
// this.s.innerHTML = this.secCounter;
console.log(this.secCounter, this.minCounter, "test");
}
在这个解决方案中,秒数每一秒都在完美地增加。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句