求教 clearTimeout无法清除定时器问题

Nomad_777 2017-11-04 12:52:56
鼠标移动到up盒子上,图片pic向上滑动,在图片还未滑动到指定位置时,再次触发onmouseover事件。
以下采用setInterval()的方法写的定时器,下一次触发onmouseover事件时,可以清除上次未执行完的动作。
<script type="text/javascript">
window.onload = function(){
var up = document.getElementById("up");
var pic =document.getElementById("pic");
var num = 0;
var speed = 20;
var timer = null;
up.onmouseover = function() {
clearInterval(timer);
timer = setInterval(fnUp,speed);
function fnUp(){
num--;
if(num >= -1070){
pic.style.top = num + "px";
} else {
clearInterval(timer);
}
};
};
</script>

但以下采用setTimeout()方法写的定时器,在下一次触发onmouseover事件时,无法清除上次未执行完的动作。
<script type="text/javascript">
window.onload = function(){
var up = document.getElementById("up");
var pic =document.getElementById("pic");
var num = 0;
var speed = 20;
var timer = null;
up.onmouseover = function(){
clearTimeout(timer);
setTimeout(fnUp,speed);
function fnUp(){
num = num -1;
if(num > -1070){
pic.style.top = num + "px";
setTimeout(fnUp,speed);
}
}
}
}
</script>
...全文
1091 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
2017-11-04
  • 打赏
  • 举报
回复
你setTimeout(fnUp,speed);没赋值 timer = setTimeout(fnUp,speed);

87,997

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧