JQuery.animate () callback infinite loop

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 one works just fine, restarting the animation after it has completed. The second just causes an endless loop.

+4
source share
5 answers

Use

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

or

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

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

+8
source

because in the first you send the function namespace, when you add () to the end of the function name, it immediately executes the function

+4
source

In your second function, you execute the function instead of passing a reference to the function, so it goes into an infinite loop.

Change the second function:

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

to

 function start() { $('#element').animate({}, 5000, 'linear', start); //Notice the change to start } 
+4
source

In the second example, you basically do a recursive call to start() .

What you want to do is pass the start of the function, as you do in the first example. The second example is the result of calling start() .

+3
source

In the second case, you call the function directly, rather than passing it as a parameter.

start() will immediately call the beginning and pass the return value to .animate() . This causes endless self-recursion.

+2
source

All Articles