clearInterval(id);请问这个函数是闭包吗
为什么clearInterval(setInterval(frame, 5)) 这样写不行,必须var id 这样子声名
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p><button onclick="myMove()">单击我</button></p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>
你理解错了,clearInterval(setInterval(frame, 5)) 情况下 frame 不可能执行
而 var id 情况下你是把 clearInterval(id) 放到了 frame 里,frame 一定会执行
而且和 clearInterval(setInterval(frame, 5)) 等价的 var id 形式是
var id = setInterval(frame, 5); clearInterval(id)