我有这个代码。这是谷歌地图api上的汽车图标动画。
$("#p_inc").mousedown(function () {
if(mouseDownAnim) clearInterval(mouseDownAnim);
moveCar();
mouseDownInc = true;
this.timer = setTimeout(function(){
if(mouseDownInc){
mouseDownAnim = setInterval(function () {
moveCar();
}, 150);
}
else{
if(mouseDownAnim) clearInterval(mouseDownAnim);
}
},200);
})
$("#p_dec").mousedown(function () {
backCar();
if(mouseDownAnim) clearInterval(mouseDownAnim);
mouseDownDec = true;
this.timer = setTimeout(function(){
if(mouseDownDec){
mouseDownAnim = setInterval(function () {
backCar();
}, 150);
}
else{
if(mouseDownAnim) clearInterval(mouseDownAnim);
}
},200);
});
$(document).on('mouseup',function(){
mouseDownInc = false;
mouseDownDec = false;
clearInterval(mouseDownAnim);
});
我期待什么?当我点击按钮然后moveCar()应该触发一次,但是当我点击并按住按钮 - moveCar()应该触发一次,等待200ms,之后应该每150ms重复一次moveCar()直到我做mouseup。它工作但有时setInterval堆栈,我不能阻止它。臭虫在哪里?
JSFIDDLE :https://jsfiddle.net/2hbkrs6m/
答案 0 :(得分:2)
工作代码
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>- jsFiddle demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<link href="/css/result-light.css" type="text/css" rel="stylesheet">
<style type="text/css"></style>
<script type="text/javascript">
$(function(){
var mouseDownInc = false;
var mouseDownDec = false;
var mouseDownAnim = null;
$("#p_inc").mousedown(function (event) {
if(mouseDownAnim) clearInterval(mouseDownAnim);
moveCar();
mouseDownInc = true;
if(mouseDownInc){
mouseDownAnim = setInterval(function () {
moveCar();
}, 150);
}
});
$("#p_dec").mousedown(function (event) {
if(mouseDownAnim) clearInterval(mouseDownAnim);
backCar();
mouseDownDec = true;
if(mouseDownDec){
mouseDownAnim = setInterval(function () {
backCar();
}, 150);
}
});
$(document).on('mouseup',function(){
mouseDownInc = false;
mouseDownDec = false;
clearInterval(mouseDownAnim);
});
function moveCar(){console.log("movecar")
}
function backCar(){console.log("backcar")
}
});
</script>
</head>
<body>
<button id="p_inc">Move</button>
<button id="p_dec">Back</button>
</body>
</html>
&#13;