My question is related to the following:
setTimeout() inside JavaScript Class using “this”
calling a function inside setTimeout and inside a function
I'm trying to implement a simple animation loop. The draw function is a member function of a state object. I'm having problems getting 'this' to work within the setTimeout and requestAnimationFrame.
I have the following code:
ANIM.State.prototype = {
constructor: ANIM.State,
play: function(){
if(!this.paused){
var that = this;
setTimeout(function(){
requestAnimationFrame(that.play);
that.setFrameNum(that.currentFrame + 1); //draw code is in here
}, 1000 / 24);
}
}
};
However, when I call play(), it runs twice and stops.
Is there a better way to do this? I'd really like to keep this function as a class function, and not a global one, if possible.