可能重複:
JS - How to clear interval after using setInterval()clearInterval()不工作
我必須改變一些文字使用setInterval
每500毫秒(我做它只是練習的JavaScript font-family
功能。)通過單擊「開」按鈕調用該功能,間隔應該使用單獨的按鈕「關」來清除。然而,「關閉」按鈕實際上並沒有清除間隔,它只是繼續。我懷疑這與範圍有關,但我不知道如何以其他方式編寫它。另外,我不想用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>
請參閱https://developer.mozilla.org/en-US/docs/DOM/window.clearInterval以瞭解'clearInterval'的實際工作原理。 –
我確實先看過MDN規範,但它並沒有幫助我解決問題。 –
window.timer = setInterval(fontChange,500); clearInterval(window.timer) – Samiul