Mickey February 2016

Clearing an interval

I'm studying Javascript and I'm having difficulties and understanding why a piece of code (see below) I edited doesn't work. The purpose is pretty simple - I want to create a button that stops and runs time back again. I even printed text to be sure my code enters the 'if' and 'else' statements, but the clearInterval doesn't seem to work. Help much appreciated!

(*the original code belongs to w3schools, I have added the "loop function" just to see if it would work, and it doesn't ;( )

This is the code:

<!DOCTYPE html>
<html>
<body>

<p>A script on this page starts this clock:</p>

<p id="demo"></p>

<button onclick="checkTime()">Stop time/Start time again</button>

<p id="test"></p>

<script>
var myCounter = 0;
var myVar = setInterval(myTimer ,1000);
function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}

function checkTime() {
    myCounter += 1;
    if (myCounter == 1) {
        clearInterval(myVar);
        document.getElementById("test").innerHTML = "ok";
    } else {
        var myVar = setInterval(myTimer ,1000);
        myCounter = 0;
        document.getElementById("test").innerHTML = "clicked again";
    }
}
</script>

</body>
</html>

Thanks!

Answers


malix February 2016

Remove the var from the second var myVar = setInterval...

The second one is scoped to your function and "overrides" the first one...

function checkTime() {
    myCounter += 1;
    if (myCounter == 1) {
        clearInterval(myVar);
        document.getElementById("test").innerHTML = "ok";
    } else {
        myVar = setInterval(myTimer ,1000);
        myCounter = 0;
        document.getElementById("test").innerHTML = "clicked again";
    }
}


seth flowers February 2016

Just glanced at your code quickly, but I notice that you are redeclaring your myVar variable, which is the variable that is being cleared when you call clearInterval due to a funky feature in javascript called hoisting.

Try the following...

<script>
var myCounter = 0;
var myVar = setInterval(myTimer ,1000);
function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}

function checkTime() {
    myCounter += 1;
    if (myCounter == 1) {
        clearInterval(myVar);
        document.getElementById("test").innerHTML = "ok";
    } else {
        myVar = setInterval(myTimer ,1000);
        myCounter = 0;
        document.getElementById("test").innerHTML = "clicked again";
    }
}
</script>

Post Status

Asked in February 2016
Viewed 2,926 times
Voted 12
Answered 2 times

Search




Leave an answer