So I tried creating an interval where users are able to toggle it. For some reason, the interval isn’t stopping.
var num = 0;
var playing = true;
function hello(){
var playInterval = setInterval(() => {
document.querySelector("#test").innerHTML = num;
num += 1;
}, 200);
if (playing == false) {
playing = true;
} else{
playing = false;
// Why is it not clearing the interval?
clearInterval(playInterval);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="test"></h1>
<button onclick="hello()">Play</button>
</body>
</html>
How could this be achieved?
>Solution :
const test = document.querySelector("#test")
const button = document.querySelector('#button')
let num = 0;
let isPlaying = false;
let playInterval;
const hello = () => {
if (!isPlaying) {
button.innerHTML = 'pause'
playInterval = setInterval(() => {
test.innerHTML = num;
num += 1;
}, 200);
} else {
button.innerHTML = 'resume'
clearInterval(playInterval);
}
isPlaying = !isPlaying
}
<h1 id="test"></h1>
<button onclick="hello()" id="button">Play</button>