我有这个代码。这是Google Maps 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/

最佳答案

工作代码



<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>

08-07 06:58