Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 works perfectly, restarting the animation after it completes. The second simply causes an infinite loop.

like image 557
Dakota Avatar asked Nov 29 '22 10:11

Dakota


2 Answers

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

like image 93
Gabriele Petrioli Avatar answered Dec 01 '22 01:12

Gabriele Petrioli


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
}
like image 39
Chandu Avatar answered Nov 30 '22 23:11

Chandu