jQuery .animate() 回调无限循环

发布于 2024-11-16 19:53:31 字数 310 浏览 4 评论 0原文

一个简单的问题:为什么我可以这样做

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

热风软妹 2024-11-23 19:53:31

则使用

function start() {
    $('#element').animate({}, 5000, 'linear', start);
}

或第二种情况很有用。

function start() {
    $('#element').animate({}, 5000, 'linear', function(){ start(); });
}

如果您想实际传递一些参数来启动,

Either use

function start() {
    $('#element').animate({}, 5000, 'linear', start);
}

or

function start() {
    $('#element').animate({}, 5000, 'linear', function(){ start(); });
}

second case is useful if you want to actually pass some arguments to start..

勿挽旧人 2024-11-23 19:53:31

在第二个函数中,您正在执行该函数而不是传递对该函数的引用,因此它会进入无限循环。

将第二个函数从: 更改

function start() {
 $('#element').animate({}, 5000, 'linear', start());
}

function start() {
  $('#element').animate({}, 5000, 'linear', start); //Notice the change 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:

function start() {
 $('#element').animate({}, 5000, 'linear', start());
}

to

function start() {
  $('#element').animate({}, 5000, 'linear', start); //Notice the change to start
}
一梦等七年七年为一梦 2024-11-23 19:53:31

这是因为在第一个中您发送了函数的名称空间,当您将 () 添加到函数名称的末尾时,它会立即执行该函数

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

涙—继续流 2024-11-23 19:53:31

在第二个示例中,您基本上是对 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().

山色无中 2024-11-23 19:53:31

在第二种情况下,您直接调用该函数,而不是将其作为参数传递。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文