<分区>
Possible Duplicate:
JS - How to clear interval after using setInterval()
我有一个函数,它使用 setInterval
每 500 毫秒更改一些文本的 font-family
(我这样做只是为了练习 JavaScript。)该函数被调用单击“打开”按钮,应该使用单独的按钮“关闭”清除间隔。但是,“关闭”按钮实际上并没有清除间隔,它只是继续。我怀疑这与范围有关,但我不确定如何以任何其他方式编写它。另外,我不想用 jQuery 来做这件事,因为毕竟我这样做是为了学习。
<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>