为了账号安全,请及时绑定邮箱和手机立即绑定

timer=null;为什么要作为全局变量。如果声明timer=null;为局部变量,就会出问题,一直没搞懂

timer=null;为什么要作为全局变量。如果声明timer=null;为局部变量,就会出问题,一直没搞懂

carey2015 2016-01-16 13:15:40
<script type="text/javascript"> //var timer=null; window.onscroll=function(){ var scrollT=document.documentElement.scrollTop||document.body.scrollTop; var top=scrollT+(document.documentElement.clientHeight-$("box").offsetHeight)/2; showmove(top);}function showmove(target){ var timer=null; clearInterval(timer); timer=setInterval(function(){ var timer=null; var speed=(target-$("box").offsetTop)/8; speed=speed>0?Math.ceil(speed):Math.floor(speed); if ($("box").offsetTop==target) { clearInterval(timer); }else{ $("box").style.top=$("box").offsetTop+speed+"px"; document.title=speed; $("box1").style.top=$("box").offsetTop+speed+"px"; } },100)}function $(id){ return document.getElementById(id);}</script>
查看完整描述

1 回答

已采纳
?
李晓健

TA贡献1036条经验 获得超461个赞

因为如果你把 timer 定义到showmove 这个方法里面,每调用一次这个方法,就会重新定义一次,所以上一次调用时启动了一个定时器,你在下一次调用这个方法时,就会重新去定义一次timmer,上一次的定时器的引用就会被覆盖,然后timmer指向的就是这一次的定时,上次的没没有办法取消了。在在showmove方法里 最上面的 clearInterval(timer);就是为了取消上一次的定时,你在这行上面又重拳定义了一个 timmer = null ; 所以clearInterval(timer); 这里面的timer就一直是空,并不是你上一次调用的这个方法启动的定时器,所以页面就会同时存在很多定时器。

查看完整回答
5 反对 回复 2016-01-16
  • 1 回答
  • 0 关注
  • 1937 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信