在javascript中使用setTimeout来做简单的动画
我正在使用 setTimeout 在 Javascript 中创建动画,但它似乎不起作用。仅执行动画的第一个动作,不再执行后续动作。
我在两台不同的笔记本电脑上使用 Firefox 进行了尝试,其中一台没有抛出任何错误,但另一台显示 self.animateCallback 不是函数
。当我尝试 diff 方法时,我还看到其他错误,例如说我的超时函数无用或“编译后运行”。似乎没有让它发挥作用。我尝试了 "function(self){self.animateCallback()}"
和 "self.animateCallback"
(带引号和不带引号)。
代码如下,它是原型方法的一部分。
increment : function(incr, target, tick) {
var self = this;
self.animateCallback = function()
{
var done = Math.abs(self.currValue - target) < Math.abs(incr);
if(!self.animateCallback || done) {
if(done) {
self.updateAngle(self.currValue/self.maxValue);
self.stopAnimation(); //just setting animateCallback to null
}
}
else
{
self.updateAngle((self.currValue+incr)/self.maxValue);
setTimeout(self.animateCallback, tick);
}
}
self.animateCallback.call();
},
I am using setTimeout to create animation in Javascript, but it does not seem to work. Only the 1st move of the animation is executed, no subsequent moves.
I tried on two different laptops using Firefox, one doesn't throw any error, but the one says self.animateCallback is not a function
. I also see other errors like saying my timeout function is useless or "compile-and-go" when I tried diff ways. Doesn't seem to get it working. I tried "function(self){self.animateCallback()}"
and "self.animateCallback"
(with and without quotes).
The code is below, it is part of a prototype method.
increment : function(incr, target, tick) {
var self = this;
self.animateCallback = function()
{
var done = Math.abs(self.currValue - target) < Math.abs(incr);
if(!self.animateCallback || done) {
if(done) {
self.updateAngle(self.currValue/self.maxValue);
self.stopAnimation(); //just setting animateCallback to null
}
}
else
{
self.updateAngle((self.currValue+incr)/self.maxValue);
setTimeout(self.animateCallback, tick);
}
}
self.animateCallback.call();
},
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我感觉问题与 setTimeout(self.animateCallback... 行有关,该行通过闭包和属性访问函数。至少它应该更整洁,这样做:
I've got a feeling the problem has something to do with the line
setTimeout(self.animateCallback...
, which is accessing the function through a closure and a property. It should be neater, at least, to do it like this:我认为错误在于其他一些代码正在将 self.animateCallback 的值更改为其他值。第一次,
setTimeout
具有正确的self.animateCallback
值,但在第一次之后,self.animateCallback
的值发生了变化到其他东西,它不是一个函数,但仍然是一个非假值,因此!self.animateCallback
返回 false。您可以尝试将 if 语句更改为:
I think the error is that some other code is changing the value of
self.animateCallback
to something else. The first time through,setTimeout
has the correct value forself.animateCallback
, but after the first time, the value ofself.animateCallback
has changed to something else, which isn't a function, but is still a non-falsy value so that!self.animateCallback
returns false.You can try changing the if statement to this:
尝试将匿名函数传递给
setTimeout
,希望它会有所帮助。
try to pass an anonymous function to
setTimeout
, likehope it'll help.