jQuery .animate() callback infinite loop

前端 未结 5 880
我在风中等你
我在风中等你 2021-02-10 23:54

A simple question: Why can I do this

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

but not this

相关标签:
5条回答
  • 2021-02-11 00:38

    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
    }
    
    0 讨论(0)
  • 2021-02-11 00:38

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

    0 讨论(0)
  • 2021-02-11 00:39

    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.

    0 讨论(0)
  • 2021-02-11 00:47

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

    0 讨论(0)
  • 2021-02-11 00:47

    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

    0 讨论(0)
提交回复
热议问题