clearInterval() not working

Matt Sanchez picture Matt Sanchez · Feb 2, 2013 · Viewed 117.1k times · Source

Possible Duplicate:
JS - How to clear interval after using setInterval()

I have a function that changes the font-family of some text every 500 ms using setInterval (I made it just to practice JavaScript.) The function is called by clicking on an "on" button and the interval is supposed to be cleared using a separate button, "off". However, the "off" button doesn't actually clear the interval, it just continues. I suspect that this has something to do with scope but I'm not sure how to write it any other way. Also, I don't want to do this with jQuery because, after all, I'm doing it to learn.

<body>
<p><span id="go" class="georgia">go</span> Italian</p>
<p>
    <button id="on" type="button" value="turn on">turn on</button>
    <button id="off" type="button" value="turn off">turn off</button>
</p>

<script>
var text = document.getElementById("go");
var on = document.getElementById("on");
var off = document.getElementById("off");

var fontChange = function() {
    switch(text.className) {
        case "georgia":
            text.className = "arial";
            break;
        case "arial":
            text.className = "courierNew";
            break;
        case "courierNew":
            text.className = "georgia";
            break;      
    }
};

on.onclick = function() {
    setInterval(fontChange, 500);
};

off.onclick = function() {
    clearInterval(fontChange);
}; 
</script>
</body>

Answer

Konstantin Dinev picture Konstantin Dinev · Feb 2, 2013

setInterval returns an ID which you then use to clear the interval.

var intervalId;
on.onclick = function() {
    if (intervalId) {
        clearInterval(intervalId);
    }
    intervalId = setInterval(fontChange, 500);
};

off.onclick = function() {
    clearInterval(intervalId);
};