Search code examples
jqueryjquery-animatejquery-callback

jquery animation briefly stutters


I have a very simple page with a block as such:

#block {
    width: 50px;
    height: 50px;
    background: red;
    visibility: hidden;
}

jquery code as follows:

var block = $('#block');
function changecol() {
    block.animate({width: 100, height: 100}, 300, function() {
        block.animate({width: 50, height: 50}, 300, changecol());
    });
}
$(document).ready(function() {
    block.css('visibility', 'visible');
    changecol();
})

So I'm trying to start a chain of callback functions and it's working.
The problem I have is a short pause in the very first animation (during the first block "growth"). It stops for (maybe?) 1.5 seconds and then it will run smoothly.
Any idea why that happens?


Solution

  • Get rid of the () in your second callback:

    var block = $('#block');
    
    function changecol() {
        block.animate({width: 100, height: 100}, 300, function() {
            // just changecol instead of changecol() here
            block.animate({width: 50, height: 50}, 300, changecol);
        });
    }
    
    $(document).ready(function() {
        block.css({visibility:'visible'});
        changecol();
    });
    

    jsFiddle to prove it