Reputation: 3025
I've got a recursing function that's stepping the animation of an element on the page:
_this = this;
this.x = 0, this.y = 0;
this.targX = 5, this.targY = 5;
this.go = function(){
var xDir = 0, yDir = 0, finished = false;
if(this.x>this.targX){
console.log("Reverse x");
xDir = -1;
}else if(this.x<this.targX){
console.log("Forward x");
xDir = 1;
}else{
xDir = 0;
if(this.y>this.targY){
console.log("Reverse y");
yDir = -1;
}else if(this.y<this.targY){
console.log("Forward y");
yDir = 1;
}else{ finished = true; }
}
this.x+= xDir;
this.y+= yDir;
if(finished==false){
this.$c.animate({
left: "+="+32*xDir,
top: "+="+32*yDir
}, 200, _this.go());
}
}
Hopefully this is clear from the code, but the animation is supposed to step in the x-direction first until this.x
= this.targX
, then step in the y-direction until this.y
= this.targY
. In this case, the element goes right 5 steps, then down 5 steps.
However, in practice, the animation goes down 5 steps then right 5 steps - as if the animation queue is being reversed. If I remove the _this.go()
call on success, the element goes right one step and stops - so I know I don't have my axes confused somewhere. The console logging even reports in the correct order:
Forward x
Forward x
Forward x
Forward x
Forward x
Forward y
Forward y
Forward y
Forward y
Forward y
What's going on here, why is the animation queue executing in reverse? Am I doing something wrong, or is this expected behavior for JQuery?
EDIT: Fiddle here: http://jsfiddle.net/WdYvB/
Upvotes: 0
Views: 242
Reputation: 262939
By writing:
this.$c.animate({
left: "+=" + 32 * xDir,
top: "+=" + 32 * yDir
}, 200, _this.go());
You're actually calling go()
and passing the value it returns (undefined
in our case) to animate()
.
You should pass the function itself instead:
this.$c.animate({
left: "+=" + 32 * xDir,
top: "+=" + 32 * yDir
}, 200, _this.go);
Upvotes: 3
Reputation: 43235
Your callback function is being called when you are assigning the callback.
if(finished==false){
this.$c.animate({
left: "+="+32*xDir,
top: "+="+32*yDir
}, 200, _this.go()); // should be _this.go
}
Upvotes: 0