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

Yan*_*nnB 2 javascript oop class

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

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

HTML

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
  <body>
    <div class="container">
      <p id="timer">im here</p>
    </div>
    <button>Start/Stop Timer</button>
    <button>Reset Timer</button>
    <script src="script.js"></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

JS

class Timer {
  constructor(){
    this.isRunning = false;
    this.currTimer = 0;
    this.runTimer;
    var timer = document.getElementById('timer');
  }

  start(){
    this.isRunning = true;
    if (this.isRunning) {
      var currentTime = this.currTimer;
      this.runTimer = setInterval(function(){
        timer.innerHTML = ++currentTime;
      },1000)
    }
  }

  pause(){
    this.isRunning = false;
    if (this.isRunning = false) {
      clearInterval(this.runTimer)
    }
  }
}

var test = new Timer();
test.start();
test.pause();// put this after a few seconds
Run Code Online (Sandbox Code Playgroud)

我也很确定我用错了“这个”。我刚刚学习了这些新东西并尝试构建它。

T.J*_*der 5

如果你想在对象被构造后使用它,你的timer局部变量需要是一个属性,所以在构造函数中,更改

var timer = document.getElementById('timer');
Run Code Online (Sandbox Code Playgroud)

this.timer = document.getElementById('timer');
Run Code Online (Sandbox Code Playgroud)

然后在 中start,您还需要使用this.timer- 这意味着您要使用箭头函数,而不是传统函数,用于setInterval回调以便函数关闭this。您可能想this.currTimer直接使用而不是将其复制到变量:

this.runTimer = setInterval(() => {
    this.timer.innerHTML = ++this.currTimer;
},1000);
Run Code Online (Sandbox Code Playgroud)

那里的逻辑也需要调整:您刚刚分配truethis.isRunning,因此之后无需检查它。但实际上,您想事先检查一下:

start(){
  if (!this.isRunning) {
    this.isRunning = true;
    this.runTimer = setInterval(() => {
      this.timer.innerHTML = ++this.currTimer;
    },1000);
  }
}
Run Code Online (Sandbox Code Playgroud)

在进行这样的比较时,您还需要使用==or ===, not =

if (this.isRunning = false) { // Needs == or ===
Run Code Online (Sandbox Code Playgroud)

但是 中的逻辑pause有一个问题:您刚刚设置this.isRunningfalse,因此在下一行检查它,它将始终为假。相反,在分配给它之前检查它。此外,使用 just if (flag)orif (!flag)而不是使用== trueor == false

pause(){
  if (this.isRunning) {
    clearInterval(this.runTimer)
    this.isRunning = false;
  }
}
Run Code Online (Sandbox Code Playgroud)

似乎适用于这些更改:

var timer = document.getElementById('timer');
Run Code Online (Sandbox Code Playgroud)
this.timer = document.getElementById('timer');
Run Code Online (Sandbox Code Playgroud)


我还强烈建议;始终使用(例如在调用 之后setInterval)。JavaScript 具有自动分号插入 (ASI),因此即使您没有在某些地方包含分号,它也会像您在某些地方包含分号一样,但是除非您对 ASI 规则有非常透彻的了解,否则您不能依赖它。