jQuery .animate() 回调无限循环
一个简单的问题:为什么我可以这样做
var start = function() {
$('#element').animate({}, 5000, 'linear', start);
}
而不是这个
function start() {
$('#element').animate({}, 5000, 'linear', start());
}
?
第一个完美地工作,完成后重新启动动画。第二个只会导致无限循环。
A simple question: Why can I do this
var start = function() {
$('#element').animate({}, 5000, 'linear', start);
}
but not this
function start() {
$('#element').animate({}, 5000, 'linear', start());
}
?
The first works perfectly, restarting the animation after it completes. The second simply causes an infinite loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
则使用
或第二种情况很有用。
如果您想实际传递一些参数来启动,
Either use
or
second case is useful if you want to actually pass some arguments to start..
在第二个函数中,您正在执行该函数而不是传递对该函数的引用,因此它会进入无限循环。
将第二个函数从: 更改
为
In your second function you are executing the function instead of passing a reference to the function, hence it's going into an infinite loop.
Change your second function from:
to
这是因为在第一个中您发送了函数的名称空间,当您将 () 添加到函数名称的末尾时,它会立即执行该函数
it's because in the first one you are sending the namespace of the function, when you add the () to the end of the function name it executes the function immediately
在第二个示例中,您基本上是对
start()
进行递归调用。您想要做的是传递函数 start 本身,就像您在第一个示例中所做的那样。您的第二个示例仅提供调用
start()
的结果。In the second example, you are basically doing a recursive call to
start()
.What you want to do is pass the function start itself, like you are doing in your first example. Your second example is only providing the result of calling
start()
.在第二种情况下,您直接调用该函数,而不是将其作为参数传递。
start()
将立即调用 start,并将其返回值传递给.animate()
。这导致了无限的自递归。In the second case, you're calling the function directly, instead of passing it as a parameter.
start()
will call start immediately, and pass the return value of that to.animate()
. This causes the infinite self recursion.