<!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