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>
setInterval
returns an ID which you then use to clear the interval.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:
and later
There are errors in your functions, but the first thing you should do, is to set the body tag correctly:
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):
You don't need this anymore, so delete it:
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. ;)
You're using clearInterval incorrectly.
This is the proper use:
Set the timer with
and then
i think you should do:
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