I am having issues where I am trying to animate an element. I have a recursive function animate that contains setTimeout to delay the animation. The issue is that the next line after the recursive method is called gets run before the animation is called. For example with this code:
this.slideTo = function(x,y) {
var originalStyle = this.element.style.cssText;
var endX = x;
var endY = y;
var pos = this.getPosition();
var startX = pos.x;
var startY = pos.y;
var distX = x - pos.x;
var distY = y - pos.y;
var totalDistance = Math.sqrt((distX*distX) + (distY*distY));
var count = 0;
var done = false;
animate(this.element);
function animate(element) {
count += 5;
var curPos = _(element).getPosition();
var curDistX = endX - curPos.x;
var curDistY = endY - curPos.y;
var curDistance = Math.sqrt((curDistX*curDistX) + (curDistY*curDistY));
var percentDone = count/totalDistance;
var moveToX = Math.round((percentDone*distX) + startX);
var moveToY = Math.round((percentDone*distY) + startY);
_(element).moveTo(moveToX,moveToY);
if(percentDone <= 1) {
setTimeout(function(){animate(element);},1);
} else {
done = true;
}
}
console.log(done);
this.element.style.cssText = originalStyle;
}
The console displays false because it is run before the animation is done. How can I solve this? btw: this is being called on a mouse event. Could that have anything to do with it?
Try next little changed code: