[javascript] clearInterval() not working

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>

This question is related to javascript scope setinterval clearinterval

The answer is


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);
}; 

The setInterval function returns an integer value, which is the id of the "timer instance" that you've created.

It is this integer value that you need to pass to clearInterval

e.g:

var timerID = setInterval(fontChange,500);

and later

clearInterval(timerID);

There are errors in your functions, but the first thing you should do, is to set the body tag correctly:

<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>
</body>

<script>....</script>

The problem sometimes may be, that you call 'var text' and the other vars only once, when the script starts. If you make changements to the DOM, this static solution may be harmful.

So you could try this (this is more flexible approach and using function parameters, so you can call the functions on any element):

<body>
<p><span id="go" class="georgia">go</span> Italian</p>
<p>
    <button type="button" value="turn on"
         onclick=turnOn("go")>turn on</button>
    <button type="button" value="turn off"
         onclick=turnOff()>turn off</button>
</p>
</body>

<script type="text/JavaScript">
var interval;

var turnOn = function(elementId){
    interval = setInterval(function(){fontChange(elementId);}, 500);
};

var turnOff = function(){
    clearInterval(interval);
};

var fontChange = function(elementId) {
    var text = document.getElementById(elementId);
    switch(text.className) {
        case "georgia":
            text.className = "arial";
            break;
        case "arial":
            text.className = "courierNew";
            break;
        case "courierNew":
            text.className = "georgia";
            break;      
    }
};
</script>

You don't need this anymore, so delete it:

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

This is dynamic code, meaning JS code which runs generic and doesn't adress elements directly. I like this approach more than defining an own function for every div element. ;)


The setInterval method returns an interval ID that you need to pass to clearInterval in order to clear the interval. You're passing a function, which won't work. Here's an example of a working setInterval/clearInterval

var interval_id = setInterval(myMethod,500);
clearInterval(interval_id);

You're using clearInterval incorrectly.

This is the proper use:

Set the timer with

var_name = setInterval(fontChange, 500);

and then

clearInterval(var_name);

i think you should do:

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to scope

Angular 2 - Using 'this' inside setTimeout Why Is `Export Default Const` invalid? How do I access previous promise results in a .then() chain? Problems with local variable scope. How to solve it? Why is it OK to return a 'vector' from a function? Uncaught TypeError: Cannot read property 'length' of undefined Setting dynamic scope variables in AngularJs - scope.<some_string> How to remove elements/nodes from angular.js array Limiting number of displayed results when using ngRepeat A variable modified inside a while loop is not remembered

Examples related to setinterval

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead? How can I pause setInterval() functions? Can clearInterval() be called inside setInterval()? Stop setInterval clearInterval() not working Calculating Page Load Time In JavaScript Javascript setInterval not working How to start and stop/pause setInterval? How do I reset the setInterval timer? jquery function setInterval

Examples related to clearinterval

Can clearInterval() be called inside setInterval()? clearInterval() not working Code for a simple JavaScript countdown timer?