Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

clearIntveral not functioning for some reason

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading