Perform jquery asynchronous animations in a synchronous fashion

Source: Internet
Author: User

When you write a jquery animation, the animation queue is orchestrated by a callback function, but when there are too many callbacks, this code often appears:

1 $ (". Box1"). FadeIn (+,function() {2    $ (". Box2"). FadeIn (  function() {3       $ (". Box3"). Hide (+,function() {4           // Todo xxx 5 6}    )          7 })

Can this level of callbacks be done in a chained style?

such as: F (fn1). f (fn2). f (fn3) ... Indicates that fn1 execution completes after fn2,fn2 execution Fn3, ...

The following steps are implemented:

1, determine the structure:

To implement chained calls, the return value of f () is required to contain an object of its own

function f (n) {   var obj = {};    = F;    return obj;}

This constructs the basic structure of chained calls.

Try adding parameters:

function f (n) {   console.log (n);    var obj = {};    function (m) {return  f (m);};    return obj;}

The result is the same as we expected, but as a result, the F call () immediately takes the parameters into execution. Now add a demand, want F (). f (). f () ... Represents only one sequence, and the actual execution requires that I release other commands before they occur. So we need to add a function run () to obj in F (), which is used to release the execution instructions and modify the code as follows:

1 function f (n) {2    var obj = {}; 3    function (m) {return  f (m);}; 4    function () {5       console.log (n)6   }7     return  obj; 8 }

As you can see, there is no output in our original code, and what happens when we execute run ()?

You can see that only the third result is output, because run () does not save the values of the first two F () parameters, and we expect to execute three times F (), which is actually only a third time. So how to solve this problem, in other words: How to save all the previously obtained F () parameters in run ()?

2. Save the parameters:

We know that the function obtains the value of the function's external variable through the parameter, and here we save all the parameters of F () in this way, the code is modified as follows:

1 functionF (n,fn) {2     varobj = {};3Obj.arr = fn===undefined?[]:[FN];4 Obj.arr.push (n);5OBJ.F =function(m) {returnf (m,n);};6Obj.run =function(){7$.each (Obj.arr,function(I,FN) {8 fn ();9          });Ten     } One     returnobj; A}

F () adds a Obj.arr array to hold all incoming arguments, and run () uniformly executes all incoming arguments, and the second parameter of F () is the last passed parameter, so that the parameters required for the last execution are saved. We'll switch the incoming parameters into functions and test them with the following code:

We can see that this is the result we want.

Append back again, want to Output 1 2 3, but actually output only after two results, because the second parameter of F () saves only the last parameter passed in, not the previous several

The second parameter of F () is an array that holds the parameters that were passed in the previous several times and modifies the code as follows:

function F (n,ar) {    var obj = {};        = ar===undefined? []:ar;      Obj.arr.push (n);        function (m) {return  F (M,obj.arr);};         function () {              $.each (Obj.arr,function(I,FN) {                  fn (     );}); return obj;}

Execute the previous code again, as expected.

3. Execute callback

F (    function  () {       $ (". Box1"). FadeIn (+);    }  ). F (     function  () {        $ (". Box2"). FadeIn (+);    }). Run ();

To execute the above code, we want to see Box1 fade in 1 seconds, and after the animation is executed, Box2 starts to fade in 1 seconds, but in fact, the two animations are executed almost simultaneously, so the next key is how to execute the callback. Modify the test code as follows:

F (    function  (CB1) {       $ (". Box1"). FadeIn (+CB1);    }  ). F (     function  (CB2) {        $ (". Box2"). FadeIn (+CB2);    }). Run ();

We see that CB1 and CB2 perform animation callbacks for Box1 and Box2 respectively, that is, we want to achieve this effect: in CB1, perform the Box2 animation, perform the subsequent animation in CB2 (if any), that is, the need to release the command in CB to execute the function in the next F (). The run () only controls the execution of the current carrying function of f () and modifies the code as follows:

functionF (n,ar) {varobj = {}; Obj.arr= ar===undefined?[]:ar;       Obj.arr.push (n); OBJ.F=function(m) {returnf (M,obj.arr);}; Obj.run=function(){             varfn =Obj.arr.shift (); if(typeoffn = = = "function") FN (callback); }       functioncallback () {Obj.run (); }   returnobj;}
F (    function  (CB) {       $ (". Box1"). FadeIn (+, CB);    }  ). F (     function  (CB) {        $ (". Box2"). FadeIn (+, CB);    }). Run ();

Execute the above code again to test, implement Box1 execution Box2, target implementation

Perform jquery asynchronous animations in a synchronous fashion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.