Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  193] [ 5]  / answers: 1 / hits: 165703  / 12 Years ago, sat, february 2, 2013, 12:00:00

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>

More From » scope

 Answers
137

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

[#80456] Friday, February 1, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalistaz

Total Points: 0
Total Questions: 100
Total Answers: 106

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;