Created
March 2, 2010 15:12
-
-
Save cowboy/319568 to your computer and use it in GitHub Desktop.
Serial asynchronous actions...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Comments for http://bjam.in/jquery-queue | |
// Say you want to execute first_async_action() followed by | |
// second_async_action(), followed by third_async_action(). | |
// You could do this: | |
first_async_action(function(){ | |
second_async_action(function(){ | |
third_async_action(function(){ | |
alert( 'done!' ); | |
}); | |
}); | |
}); | |
// Or if that looks messy (which it does) you could try | |
// something like this: | |
function start(){ | |
first_async_action( exec_second_async_action ); | |
}; | |
function exec_second_async_action(){ | |
second_async_action( exec_third_async_action ); | |
}; | |
function exec_third_async_action(){ | |
third_async_action( all_done ); | |
}; | |
function all_done(){ | |
alert( 'done!' ); | |
}; | |
start(); | |
// But what if you decide you need to execute third_async_action | |
// before second_async_action? either way, it's messy. A good, | |
// flexibile, solution would be to do this kind of thing, which | |
// is pretty much what jQuery's queuing methods do, internally. | |
// Not to mention that when operating on a queue, it's easy to | |
// add functionality to stop the queue or skip the next item in | |
// the queue. For example, "skip next item" could be as simple | |
// as doing idx++. | |
function next(){ | |
var action = actions[ idx++ ]; | |
action && action(); | |
}; | |
var idx = 0, | |
actions = [ | |
function(){ | |
first_async_action( next ); | |
}, | |
function(){ | |
second_async_action( next ); | |
}, | |
function(){ | |
third_async_action( next ); | |
}, | |
function(){ | |
alert( 'done!' ); | |
} | |
]; | |
next(); |
You can effectively "chain" asynchronous actions using callbacks (if the method supports it):
$('.child').hide( 'slow', function(){
$('body').hide();
});
See the jQuery API .hide() documentation for another example.
Thank's for that, but I want a callback function not to be attached to .hide() or other method. In my project I need to do a complex chaining and .queue() also wouldn't work for me ((
Check this out: http://gist.github.com/330793
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I want to do things one after another (I've tried to make a simple example with two events). If I want to perform action on another element, in my case to hide body, both events happen simultaneously. Could you please give me a hint how to do every function synchronous.