User 28
User 28

Reputation: 5158

Why jQuery.animate is synchronous?

Why does this code work synchronously?

$this.animate( { 'left': '+=200px' } );
$this.animate( { 'top' : '+=200px' } );

I really doubt that it is possible to execute a function synchronously in JavaScript.

And

doSomething();
doSomethingMore();

function doSomething() {
    setTimeout(function() {
        alert('doSomething finished');
    }, 3000);
}

function doSomethingMore() {
    setTimeout(function() {
        alert('doSomethingMore finished');
    }, 1000);
}

How to not execute function doSomethingMore until function doSomething finished. Or Something like that.

Thank you.

Upvotes: 2

Views: 168

Answers (2)

Scimonster
Scimonster

Reputation: 33409

I'm just going to take a guess here, because i can't follow the jQuery source code either. :)

.animate() adds animations to a queue. By default this is $.fx. When an item is added to the queue: if it is the first, it is run; if it is not, it waits until it is the first item in the queue. Once jQuery has finished running the animation, it removes the first item from the queue (i.e. the animation that just finished), and runs what had been the second.
Therefore, it only seems to run synchronously. If you put another statement after the second call to .animate(), you'll see that it is actually executed immediately. This is also why .animate() takes a callback.

There are also other functions that let you manipulate the queue. For example .stop() and .queue().

Upvotes: 4

jayaguilar
jayaguilar

Reputation: 182

You are calling the method twice so it will do it the way it is currently working for it to work the way you want it to work you have to do in one call:

$this.animate({left: '+=200px',top : '+=200px'});

Upvotes: -1

Related Questions