如果要在构造对象后使用它,则
timer
本地变量需要改为属性,因此在构造函数中,更改
var timer = document.getElementById('timer');
到
this.timer = document.getElementById('timer');
然后进入
start
,您需要使用
this.timer
也就是说你想用
箭头函数
,而不是传统的函数,对于
setInterval
回调以便函数结束
this
。你可能想用
this.currTimer
直接复制而不是复制到变量:
this.runTimer = setInterval(() => {
this.timer.innerHTML = ++this.currTimer;
},1000);
这里的逻辑也需要调整:您刚刚分配了
true
到
this.isRunning
,所以之后不需要检查。但实际上,你需要事先检查一下:
start(){
if (!this.isRunning) {
this.isRunning = true;
this.runTimer = setInterval(() => {
this.timer.innerHTML = ++this.currTimer;
},1000);
}
}
你还需要使用
==
或
===
不是
=
,当进行这样的比较时:
if (this.isRunning = false) { // Needs == or ===
但其中的逻辑
pause
有个问题:你刚刚
这个。正在运行
到
false
,所以在下一行检查时,它总是错误的。相反,在分配给它之前检查它。另外,使用
if (flag)
或
if (!flag)
而不是使用
== true
或
== false
:
pause(){
if (this.isRunning) {
clearInterval(this.runTimer)
this.isRunning = false;
}
}
似乎可以应对这些变化:
class Timer {
constructor() {
this.isRunning = false;
this.currTimer = 0;
this.runTimer;
this.timer = document.getElementById('timer');
}
start() {
if (!this.isRunning) {
this.isRunning = true;
this.runTimer = setInterval(() => {
this.timer.innerHTML = ++this.currTimer;
}, 1000);
}
}
pause() {
if (this.isRunning) {
clearInterval(this.runTimer);
this.isRunning = false;
}
}
}
var test = new Timer();
test.start();
setTimeout(function() {
test.pause(); // put this after a few seconds
}, 4000);
<div id="timer"></div>
我也强烈建议使用
;
始终如一(例如
设置间隔
)javascript有自动分号插入(asi)功能,因此即使没有,它在某些地方也会像包含分号一样工作,但是除非有
非常
全面了解ASI规则。