【发布时间】:2015-01-24 00:13:26
【问题描述】:
我的问题与以下有关:
setTimeout() inside JavaScript Class using “this”
calling a function inside setTimeout and inside a function
我正在尝试实现一个简单的动画循环。 draw 函数是状态对象的成员函数。我在让“this”在 setTimeout 和 requestAnimationFrame 内工作时遇到问题。
我有以下代码:
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);
}
}
};
但是,当我调用 play() 时,它会运行两次并停止。
有没有更好的方法来做到这一点?如果可能的话,我真的很想将此函数保留为类函数,而不是全局函数。
【问题讨论】:
标签: javascript animation requestanimationframe