Javascript 在类中使用setInterval()和clearInterval()

Javascript 在类中使用setInterval()和clearInterval(),javascript,class,oop,Javascript,Class,Oop,我在理解如何在类中使用setInterval()和clearInterval()时遇到问题。我正在尝试构建一个从0开始直到决定停止的计时器 到目前为止,我设法找到了一个方法,当你调用它时,计时器会启动,但当我尝试暂停它时,它会忽略我的方法并继续 HTML 我也很确定我用错了“this”。 我刚刚学会了这个新东西,并试图构建它。在你的情况下,你是在分配而不是比较 这: 应该是: pause() { this.isRunning = false; if (this.isRunning ===

我在理解如何在类中使用setInterval()和clearInterval()时遇到问题。我正在尝试构建一个从0开始直到决定停止的计时器

到目前为止,我设法找到了一个方法,当你调用它时,计时器会启动,但当我尝试暂停它时,它会忽略我的方法并继续

HTML

我也很确定我用错了“this”。
我刚刚学会了这个新东西,并试图构建它。

在你的情况下,你是在分配而不是比较

这:

应该是:

pause() {
  this.isRunning = false;
  if (this.isRunning === false) {
    clearInterval(this.runTimer)
  }
}
或者,由于条件的计算结果始终为true,因此只需:

pause() {
  this.isRunning = false;

  clearInterval(this.runTimer)
}

如果要在构造对象后使用它,则需要将
计时器
局部变量改为属性,因此在构造函数中,更改

var 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
中的逻辑有一个问题:您刚刚将
设置为this.isRunning
false
,因此在下一行检查它时,它总是false。相反,在分配给它之前检查它。另外,只使用
if(flag)
if(!flag)
而不是使用
==true
==false

pause(){
  if (this.isRunning) {
    clearInterval(this.runTimer)
    this.isRunning = false;
  }
}
似乎能适应这些变化:

类计时器{
构造函数(){
this.isRunning=false;
此.currTimer=0;
这个.runTimer;
this.timer=document.getElementById('timer');
}
开始(){
如果(!this.isRunning){
this.isRunning=true;
this.runTimer=setInterval(()=>{
this.timer.innerHTML=++this.currTimer;
}, 1000);
}
}
暂停(){
如果(此.isRunning){
clearInterval(this.runTimer);
this.isRunning=false;
}
}
}
var测试=新定时器();
test.start();
setTimeout(函数(){
test.pause();//几秒钟后将其放入
}, 4000);

如果(this.isRunning=false){
-您输入了一个错误。这是一个赋值,不是一个比较。true..修复了它,但仍然不起作用。我已经回滚了修复它的编辑。问题不应该是移动目标。:-)如果(this.isRunning){clearInterval(this.runTimer);this.isRunning=false;}
但这需要对代码的其余部分进行修复。感谢您的帮助!
this.runTimer = setInterval(() => {
    this.timer.innerHTML = ++this.currTimer;
},1000);
start(){
  if (!this.isRunning) {
    this.isRunning = true;
    this.runTimer = setInterval(() => {
      this.timer.innerHTML = ++this.currTimer;
    },1000);
  }
}
if (this.isRunning = false) { // Needs == or ===
pause(){
  if (this.isRunning) {
    clearInterval(this.runTimer)
    this.isRunning = false;
  }
}