JQuery synchronous animation JQuery synchronous animation jquery jquery

JQuery synchronous animation


jQuery cannot make synchronous animations.

Remember that JavaScript runs on the browser's UI thread.

If you make a synchronous animation, the browser will freeze until the animation finishes.

Why do you need to do this?

You should probably use jQuery's callback parameter and continue your method code in the callback, like this:

function doSomething() {    var thingy = whatever;    //Do things    $('something').animate({ width: 70 }, function() {        //jQuery will call this method after the animation finishes.        //You can continue your code here.        //You can even access variables from the outer function        thingy = thingy.fiddle;    });}

This is called a closure.


I think you should take a look at the jQuery queue() method.

Not only does queue()'s doc explain jQuery animations don't really block the UI, and actually queues them after one another.

It also provides with a way to make your animations and function calls sequential (this is my best understanding of what you mean by "synchronous"), like:

$("#myThrobber")    .show("slow")                 // provide user feedback     .queue( myNotAnimatedMethod ) // do some heavy duty processing    .hide("slow");                // provide user feedback (job's myNotAnimatedMethod() { // or animated, just whatever you want anyhow...    // do stuff    // ...    // tells #myThrobber's ("this") queue your method "returns",     // and the next method in the queue (the "hide" animation) can be processed    $(this).dequeue();    // do more stuff here that needs not be sequentially done *before* hide()    // }  

This is of course overkill with asynchronous processing; but if your method is actually a plain old synchronous javascript method, that could be the way to do it.

Hope this helps, and sorry for my poor english...


jQuery provides a "step" callback for its .animate() method. You can hook into this to do synchronous animations:

jQuery('#blat').animate({  // CSS to change  height: '0px'},{  duration: 2000,  step: function _stepCallback(now,opts) {    // Stop browser rounding errors for bounding DOM values (width, height, margin, etc.)    now = opts.now = Math.round(now);    // Manipulate the width/height of other elements as 'blat' is animated    jQuery('#foo').css({height: now+'px'});    jQuery('#bar').css({width: now+'px'});  },  complete: function _completeCallback() {    // Do some other animations when finished...  }}