Reputation: 573
Hello im using an object constructor to manage some animation, in some cases i want to pass a callback when the animation is finished to make some other elements appear. The problem is if out of the if sentence i log a type of callback it is effective a function but when i do the log inside an if statement if is always undefined, i appreciate if someone could help me with this, i also leave the piece of code so you guys can check it out.
// CONSTRUCTOR WHO MANAGE THE ANIMATIONS FOR THE WEBSITE
function SpriteAnimation(frameWidth, spriteWidth, spriteElement, shouldLoop, frameRate){
this.frameWidth = frameWidth;
this.spriteWidth = spriteWidth;
this.selector = document.getElementById(spriteElement);
this.shouldLoop = shouldLoop ;
this.curPx = 0;
this.frameRate = frameRate;
}
SpriteAnimation.prototype.start = function(callback){
this.selector.style.backgroundPosition = "-" + this.curPx + "px 0px";
this.curPx += this.frameWidth;
if (this.curPx < (this.spriteWidth - this.frameWidth)){
setTimeout(this.start.bind(this), this.frameRate);
}else if (this.curPx > (this.spriteWidth - this.frameWidth)){
console.log(typeof callback);
}else if(this.shouldLoop){
this.curPx = 0;
this.start();
}
};
later in the code I instanced it and run the start:
var letter = new SpriteAnimation(790, 18163, "letter", false, 53.3);
letter.start(function(){
console.log("hola");
});
Upvotes: 0
Views: 827
Reputation: 388326
The one possibility is the start function is invoked by the setTimeout
SpriteAnimation.prototype.start = function(callback){
this.selector.style.backgroundPosition = "-" + this.curPx + "px 0px";
this.curPx += this.frameWidth;
if (this.curPx < (this.spriteWidth - this.frameWidth)){
setTimeout((function(){
this.start(callback)
}).bind(this), this.frameRate);
}else if (this.curPx > (this.spriteWidth - this.frameWidth)){
console.log(typeof callback);
}else if(this.shouldLoop){
this.curPx = 0;
this.start();
}
};
Upvotes: 1
Reputation: 146302
You did not pass the callback in your setTimeout
, I would suggest doing this:
setTimeout(function(){
this.start(callback);
}, this.frameRate);
Upvotes: 2