为什么timer必须声明在函数外面(附代码)?
timer直接在函数里声明使用的话会有bug,放在外面就没事了,求解
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>缓冲运动</title>
<style type="text/css">
*{border:0; margin:0;}
#div1{ width:200px; height:200px; background:red; position:relative; top:0; left:-200px;}
.div2{ width:20px; height:40px; background:blue; position:absolute; top:80px; left:200px;}
</style>
<script type="text/javascript">
window.onload=function(){
var div1=document.getElementById("div1");
div1.onmouseover=function(){
startMove(0);
}
div1.onmouseout=function(){
startMove(-200);
}
var timer=null;
function startMove(target){
clearInterval(timer);
timer=setInterval(function(){
var speed=(target-div1.offsetLeft)/20;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(target==div1.offsetLeft){
clearInterval(timer);
}else{
div1.style.left=div1.offsetLeft+speed+"px";
}
},30);
}
}
</script>
</head>
<body>
<div id="div1"><div class="div2"></div></div>
</body>
</html>