A queue is a linear table that allows only one end of an insert operation and another for a delete operation, and the queue is a first in, out (FIRST-IN-FIRST-OUT,FIFO) data structure
Queues are very frequent in program programming because JavaScript is single-threaded, so it can only perform one task at any one time period, and it also mixes asynchronous mechanisms.
So the problem is:
1. When the asynchronous operation is executed, the synchronization code continues, and the synchronous code relies on async, which naturally goes wrong
2. Multiple synchronized tasks are called at different time periods
In the animation of jquery, we often write a continuous animation code
$book.Animate ({0.25,} ). Animate ({0.5}). Animate ({ 1 })
The intuitive feeling for us is that the opacity of the first animate element becomes 0.25 and then proceeds to the second animate, the opacity of the element becomes 0.5, and so on. But in fact, this is an essential problem, the animation is called asynchronously, the Animate method is executed synchronously, so it needs to be designed to queue, jquery also gives a special animation design of the queue method
Queue is also a special linear table, in JavaScript we can directly use the array to implement such a design, the array of push () method can be added to the end of the array element, the shift () method can delete the first element of the array.
function Queue () { This. DataStore = []; This. Enqueue =Enqueue; This. dequeue =dequeue; This. First =First ; This. end =end; This. toString =toString; This. Empty =empty;}/////////////////////////////the Enqueue () method adds an element to the end of the queue://///////////////////////////function Enqueue (element) { This. Datastore.push (Element);}///////////////////////////the Dequeue () method deletes the elements of the first team:///////////////////////////function dequeue () {return This. Datastore.shift ();}///////////////////////////you can read the elements of the first and the end of the queue using the following methods:///////////////////////////function First () {return This. datastore[0];} Function End () {return This. datastore[ This. Datastore.length-1];}
///////////////////////////////the ToString () method displays all elements in the queue///////////////////////////////function toString () {varRetstr =""; for(vari =0; I < This. datastore.length; ++i) {retstr+= This. datastore[i] +"\ n"; } returnretstr;}//////////////////////////a method is required to determine if the queue is empty//////////////////////////function Empty () {if( This. Datastore.length = =0) { return true; } Else { return false; }}varQ =NewQueue (); Q.enqueue ("Aaron1"); Q.enqueue ("Aaron2"); Q.enqueue ("Aaron3"); Console.log ("Queue Header:"+ Q.first ());//("Aaron1");Console.log ("End of queue:"+ q.end ());//("Aaron3");
Queues use linear storage, there are some drawbacks of sequential storage, such as queuing to buy tickets, if the first bought, the back will naturally move forward a vacancy, so that the entire queue of each member to move forward, but the JavaScript queue is described in arrays, The bottom layer solves some drawbacks. Of course there are problems in finding algorithms, such as the ability to use arrays to implement single-linked list structures, and so on, and we're only talking about JavaScript queues here.
Simulating jquery, using a queue to implement an animation
<div id="Div1"style="width:100px;height:50px;background:red;cursor:pointer;color: #fff; text-align:center;line-height:50px;"> Click </div>(function ($) {window.$= $;}) (function () {varrquickexpr =/^ (?: # ([\w-]*)) $/; function Aquery (selector) {return NewAQuery.fn.init (selector); } /** * Animation * @return {[type]} [description]*/ varAnimation =function () {varSelf = {}; varQueue = [];//Animation Queue varFireing =false //Animation Lock varFirst =true;//triggered via the Add interface varGetStyle =function (obj, attr) {returnObj.currentstyle? OBJ.CURRENTSTYLE[ATTR]: getComputedStyle (obj,false) [attr]; } varMakeanim =function (element, options, func) {varwidth =Options.width//package a specific execution algorithm//CSS3//SetTimeoutElement.style.webkitTransitionDuration ='2000ms'; Element.style.webkitTransform='Translate3d ('+ width +'px,0,0)'; //end of listening animationElement.addeventlistener ('Webkittransitionend', Function () {func ()}); } var_fire =function () {//adding animations is triggering if(!fireing) { varOncerun =Queue.shift (); if(oncerun) {fireing=true; //NextOncerun (function () {fireing=false; _fire (); }); } Else{fireing=true; } } } returnSelf = { //Increase Queueadd:function (element, options) {Queue.push (function (func) {Makeanim (E Lement, Options, func); }); //If there is a queue that immediately triggers the animation if(First &&queue.length) { First=false; Self.fire (); } }, //triggeringfire:function () {_fire (); } } }(); Aquery.fn= Aquery.prototype ={run:function (options) {Animation.add ( This. element, options); return This; } } varinit = AQuery.fn.init =function (selector) {varMatch =rquickexpr.exec (selector); varelement = document.getElementById (match[1]) This. Element =element; return This; } Init.prototype=Aquery.fn; returnAquery;} ());//DomvarOdiv = document.getElementById ('Div1');//calledOdiv.onclick =function () {$ ('#div1'). Run ({'width':' -'}). Run ({'width':' -'}). Run ({'width':' +' });};
Test
<textarea style="width:600px; height:200px" id="theCode" title="双击运行代码" ondblclick="runCode(‘theCode‘);"><!doctype html><ptml><pead><meta http-equiv= "Content-type" content= "text/html; charset= Utf-8 "/><title></title></pead><body> Click </body></ptml></textarea>
Data structure and algorithm JavaScript (ii) queue