In some scenarios, the queue is indeed like a vanguard, which can bring good results. For example, it can be used with a timer to simulate the time difference effect.
Copy codeThe Code is as follows:
Function createDq (){
Var dq = [], size = 0;
Return {
SetDq: function (queue ){
Dq = queue;
Size = queue. length;
},
Queue: function (fn ){
Size ++;
Dq. push (fn );
},
Dqueue: function (){
Size --;
Return dq. shift ();
},
Run: function (fn ){
Var me = this, timer;
Timer = setInterval (function (){
If (size <= 1 ){
ClearInterval (timer );
}
Fn. call (null, me. dqueue ());
}, 30 );
}
}
}
The above is a simple implementation. In different scenarios, you can make some appropriate changes to adapt to local conditions.
The following is an animation simulating Bubble sorting. It seems pretty good to try to use the observer mode with a little bit of it.
Copy codeThe Code is as follows:
Function bubble (){
Var obs = [];
Function compare (x, y ){
Return x. w-y. w;
}
Function swap (a, I, j ){
Var t = a [I]; a [I] = a [j]; a [j] = t;
}
Function proxy (a, I, j ){
Y (a [I]. id + "-" + a [j]. id );
Swap. apply (null, arguments );
}
Function notify (arg ){
Obs [0]. m. call (obs [0], arg );
}
Return {
AddOb: function (ob ){
Obs. push (ob );
},
Sort: function (arr ){
Var len = arr. length;
For (var x = 1; x <len; x ++ ){
For (var y = 0; y <len-x; y ++ ){
If (compare (arr [y], arr [y + 1])> 0 ){
Proxy (arr, y, y + 1 );
}
}
}
}
}
}
<! DOCTYPE html "> <ptml> <style> </style> <ul id =" mop "> </ul> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]