javascript - 使用setTimeout模拟setInterval时,用clearTimeout清除多余的调用,为什么运动直接停止了?
本文介绍了javascript - 使用setTimeout模拟setInterval时,用clearTimeout清除多余的调用,为什么运动直接停止了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
使用setTimeout模拟setInterval时,使用clearTimeout清除多余的调用,为什么运动直接停止了?
html:`
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="example.css">
</head>
<body>
<input type="button" value="开始运动"/>
<div id="example">1</div>
<script src="example1.js"></script>
</body>
</html>`
css:
div{
position:absolute;
height: 200px;
width: 200px;
background: red;
left:0;
top:100px;
}
js:
var aButton = document.getElementsByTagName("input")[0];
var timer = null;
var oDIV = document.getElementById("example");
function startMove() {
clearTimeout(timer);
timer = setTimeout(function (){
if(oDIV.offsetLeft<300) {
oDIV.style.left = oDIV.offsetLeft + 10 + "px";
setTimeout(startMove,200);//位置1
}else{
clearTimeout(timer);
}
},200);
//位置2
}
aButton.onclick = function () {
startMove();
};
如果我把setTimeout(startMove,200);放在位置1,那么运动很正常,我不停的点击button,运动也不会变快或者停止。
但是如果我把setTimeout(startMove,200);放在位置2,那在我点击第二次button的时候,运动会直接停止,而且不会再继续运动了。
想请问一下,为什么会发生这种情况?就算我点击了button,前一个setTimeout被清除了,不应该在20毫秒后,又会出现一个新的setTimeout吗?
希望有高手可以解答,非常感谢!
解决方案
位置2出问题是因为多次点击会导致多次触发setTimeout(startMove,200)
,然后会在200ms内不断clearTimeout(timer)
和给timer赋值setTimeout,导致动画失效。
这篇关于javascript - 使用setTimeout模拟setInterval时,用clearTimeout清除多余的调用,为什么运动直接停止了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文