我在理解如何在类中使用 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) …Run Code Online (Sandbox Code Playgroud)