views:

3367

answers:

8

I have multiple functions the do different animations to different parts of the HTML. I would like to chain or queue these functions so they will run the animations sequentially and not at the same time.

I am trying to automate multiple events in sequence to look like a user has been clicking on different buttons or links.

I could probably do this using callback functions but then I would have to pull all of the animations from the different functions and regroup in the right pattern.

Does the jquery "queue" help? I couldn't understand the documentation for the queue.

Example, JQuery:

 function One() {
        $('div#animateTest1').animate({ left: '+=200' }, 2000);
    }
    function Two() {
        $('div#animateTest2').animate({ width: '+=200' }, 2000);
    }

// Call these functions sequentially so that the animations
// in One() run b/f the animations in Two()
    One();
    Two();

HTML:

    <div id="animatetest" style="width:50px;height:50px;background-color:Aqua;position:absolute;"></div>
    <div id="animatetest2" style="width:50px;height:50px;background-color:red;position:absolute;top:100px;"></div>

Thanks.

EDIT: I tried it with timers but I thought there is a better way to do it.

EDIT #2:

Let me be more specific. I have multiple functions bound to click & hover events on different elements of the page. Normally these functions have nothing to do with each other ( they don't reference each other). I would like to simulate a user going through these events without changing the code of my existing functions.

A: 

As far as animation interval already defined in 2000 ms, you can do second call with delay in 2000 ms:

One();
SetTimeout(function(){
  Two();
}, 2000);
Alex Pavlov
I know I can use timers or setTimeout, but I thought there was some sort of queue that I could put my functions in.
orandov
+1  A: 

Assuming you want to keep One and Two as separate functions, you could do something like this:

function One(callback) {
    $('div#animateTest1').animate({ left: '+=200' }, 2000, 
        function(e) { callback(); });
}
function Two() {
    $('div#animateTest2').animate({ width: '+=200' }, 2000);
}

// Call these functions sequentially so that the animations
// in One() run b/f the animations in Two()
    One(Two);
marcc
What would happen if the callback parameter that was passed in is 'null'? Would it still work?
orandov
No, you should dome some error handling in there. I wrote this in the SO edit box, haven't put much thought into error handling or trying to run it.
marcc
I wasn't trying to criticize your error handling skills. :) I was asking b/c when the functions will be called by the real user actually click the link there should be no callback (null). Only when the code will automate the steps would there be a need for a callback.
orandov
A: 

I would run the second as a callback function:

$('div#animateTest1').animate({ left: '+=200' }, 2000, function(){
    two();
});

which would run two() when first animation finishes, if you have more animations on timed queue for such cases i use jquery timer plugin instead setTimeout(), which comes very handy in some cases.

Sinan Y.
whats wrong with setTimeout? and how does that plugin do it better if internally it uses the said setTimeout?
redsquare
+2  A: 

I'd create an array of functions and add every function you want to queue to it.

Then I'd append a function call which loops through the array and calls each function to the event through jQuery.

You could probably create a very simple plugin for jQuery that could handle this internally as well.

Spencer Ruport
I think your idea will break if the function to be queued is asynchronous and if author wants to wait for asynchronous function to wait before running the next function in the list.
SolutionYogi
+2  A: 

On one of my web projects, I had to perform various sequences of actions depending on what event fired. I did this using callbacks (something like the Visitor pattern). I created an object to wrap any function, or group of actions. Then I would queue those wrappers; an array works fine. When the event fired, I would iterate over the array, calling my object's specialized method that took a callback. That callback triggered my iteration to continue.

To wrap a function, you need knowledge of the apply function. The apply function takes an object for scope and an array of arguments. That way you don't need to know anything about the functions you are wrapping.

geowa4
+6  A: 

The jQuery Queue code is not as well documented as it could be, but the basic idea is this:

$("#some_element").queue("namedQueue", function() {
  console.log("First");
  var self = this;
  setTimeout(function() {
    $(self).dequeue("namedQueue");
  }, 1000);
});

$("#some_element").queue("namedQueue", function() {
  console.log("Second");
  var self = this;
  setTimeout(function() {
    $(self).dequeue("namedQueue");
  }, 1000);
});

$("#some_element").queue("namedQueue", function() {
  console.log("Third");
});

$("#some_element").dequeue("namedQueue");

If you run this code, you will see "First" in the console, a pause of 1s, see "Second" in the console, another pause of 1s, and finally see "Third" in the console.

The basic idea is that you can have any number of named queues bound to an element. You remove an element from the queue by calling dequeue. You can do this yourself manually as many times as you want, but if you want the queue to run automatically, you can simply call dequeue inside the queued up function.

Animations in jQuery all run inside a queue called fx. When you animate an element, it automatically adds the new animation on the queue and calls dequeue if no animations are currently running. You can insert your own callbacks onto the fx queue if you wish; you will just need to call dequeue manually at the end (as with any other queue use).

Yehuda Katz
$('div#myDiv1').queue('fx',fn1);$('div#myDiv2').queue('fx',fn2);Notice that they are executed in parallel, not sequentially.Therefore if you have two functions, with animate() on different elements, they will also execute in parallel. Thus, just using queues will not allow sequential execution.
A: 

The following will work and will not error if callback is null:

function One(callback)
{
    $('div#animateTest1').animate({ left: '+=200' }, 2000, 
       function()
       {
            if(callback != null)
            {
                 callback();
            }
       }
    );
}
function Two()
{
    $('div#animateTest2').animate({ width: '+=200' }, 2000);
}

var callback = function(){ Two(); };
One(callback);
TrippRitter
A: 

@TrippRitter gotta attach .call to the callback

One = function(callback){
    $('div#animateTest1').animate({ left: '+=200' }, 2000, function(){
        if(typeof callback == 'function'){
            callback.call(this);
        }
    });
}

Two = function(){
    $('div#animateTest2').animate({ width: '+=200' }, 2000);
}

One(function(){ 
    Two();
});

but its is the same as doing the following

$('div#animateTest1')
    .animate({ left: '+=200' }, 2000, 
    function(){
       Two();
    });

Two = function(){
    $('div#animateTest2').animate({ width: '+=200' }, 2000);
}
twenjamin