Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created March 2, 2010 15:12
Show Gist options
  • Save cowboy/319568 to your computer and use it in GitHub Desktop.
Save cowboy/319568 to your computer and use it in GitHub Desktop.
Serial asynchronous actions...
// 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();
@tylik
Copy link

tylik commented Jun 17, 2010

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.

 var $anchor = $( '.child' );
 function first () { $anchor.hide( 'slow' ) };
 function second () { $( 'body' ).hide() };
 first( second() );
 

@cowboy
Copy link
Author

cowboy commented Jun 17, 2010

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.

@tylik
Copy link

tylik commented Jun 17, 2010

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

@cowboy
Copy link
Author

cowboy commented Jun 17, 2010

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment