jQuery .animate() callback infinite loop

落爺英雄遲暮 提交于 2020-01-01 03:30:08

问题


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.


回答1:


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..




回答2:


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




回答3:


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
}



回答4:


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().




回答5:


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.



来源:https://stackoverflow.com/questions/6461945/jquery-animate-callback-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!