私は2つの関数animateLeftとanimateRightを使って前後にボックスをアニメーション化する単純なページを持っています。私はこのようなアニメーションを呼び出すと、それが正常に動作します:JQueryアニメーションコールバック
$("#divTestBox3").animate({ "left" : "200px" }, 1000, animateLeft);
しかし、私はこのようにそれを呼び出すとき:
$("#divTestBox3").animate({ "left" : "200px" }, 1000, animateLeft());
関数animateLeft()アニメーションが前に完了するまで待ちません実行します。 animateLeft()がすぐに呼び出され、スタックオーバーフローが発生します。誰かが私にこれら2つの行の違いを理解してもらうことができますか、なぜ彼らは異なった動作をしますか?
完全なアプリケーションを以下に示します。
<head>
<script src="../JSCommon/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var stop = false;
$(document).keydown(function(event) {
stop = !stop;
if (!stop)
animateRight();
});
function animateRight() {
if(!stop) {
console.log('animateRight');
$("#divTestBox3").animate({ "left" : "200px" }, 1000, animateLeft);
}
}
function animateLeft() {
if(!stop) {
console.log('animateLeft');
$("#divTestBox3").animate({ "left" : "20px" },1000,animateRight);
}
}
});
</script>
</head>
<body>
<div style="height: 40px;">
<div id="divTestBox3" style="height: 20px; width: 20px; left: 20px; background-color: #89BC38; position: absolute;"></div>
</div>
<p>Press any key to start/stop the animation</p>
</body>