I have a problem understanding how to use setInterval() and clearInterval() in classes. I'm trying to build a timer that starts from 0 until i decide to stop it.
Up to now i managed to have a method that when you call it, the timer starts but when i try to pause it it just ignores my method and continues.
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>
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
I'm also pretty sure i'm using "this" wrong. I just learned this new stuff and trying to build it.