<!DOCTYPE html>
<html lang="en">
<head>
<title>Lab 10</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body style="background-color:lightgreen;">
<input type="button" id="btnSetInterval" value="log every 3 seconds" ><br />
<input type="button" id="btnCancelSetInterval" value="cancel the logging every 3 seconds"><br />
<input type="button" id="btnSetTimeout" value="create an event to run 3 seconds from now" /><br />
<input type="button" id="btnCancelSetTimeout" value="cancel the event that is supposed to run 3 seconds from now" />
<script type="text/javascript">
$(document).ready(function() {
var intervalID;
var timeoutID;
function setIntervalCounter() {
var intervalID = setInterval(function() {
console.log("Hello World");
}, 3000)
}
function stopIntervalCounter() {
clearInterval(intervalID);
};
$("#btnSetInterval").click(setIntervalCounter);
$("#btnCancelSetInterval").click(stopIntervalCounter);
});
</script>
</body>
//當我按下第一個按鈕時,計數器開始,但我無法停止計數器。 //我希望這是添加評論的正確方式,有時我在視圖中丟失我的代碼 //我知道這個問題被多次詢問,並且我嘗試了所有解決方案。 :( 爲什麼我的clearInterval不起作用?
要創建一個新的局部變量'intervalID'而不是使用前一個。從函數'setIntervalCounter'刪除var – nmoliveira