Scene:
Do live, there will be admission information, entrance special effects, if the user has a mount, you need to show him a few seconds of the mount effect, if several people at the same time, how to show it? That's when you think of the settimeout function, yes, well thought out, but how does the asynchronous function queue come true? Directly on the code:
varQueue =function () { This. List = []; }; Queue.prototype={constructor:queue, queue:function (FN) { This. List.push (FN)return This; }, Wait:function (ms) { This. List.push (ms)return This; }, Dequeue:function () {varSelf = This, List=self.list; Self.isdequeue=true; varel = List.shift () | |function () {}; if(typeofel = =" Number") {setTimeout (function () {self.dequeue (); }, EL); } Else if(typeofel = ="function") {El.call ( This) if(list.length) {self.dequeue (); } Else{self.isdequeue=false; } } } };
Example:
If A and B come in almost simultaneously;
C in When a, B has not fully out of the queue, come in;
D came in after the A,b,c all but the queue.
varQ =NewQueue (); functionA () {Console.log ("A was executed",NewDate ()); } functionB () {Console.log ("B executed",NewDate ()); } functionC () {Console.log ("C was executed",NewDate ()); } functiond () {Console.log ("D carried out",NewDate ()); } q.wait (2000); Q.queue (a); Q.wait (2000); Q.queue (b); Q.dequeue (); SetTimeout (function(){//3S came in later.Q.wait (2000); Q.queue (c); },3000); SetTimeout (function(){//8S came in later.Q.wait (2000); Q.queue (d); Q.dequeue (); },8000);
Here we need to decide when to call Dequeue to get out of the queue. ( Why is C in the queue, do not need to dequeue, but d in the time you need to dequeue it?) )
But in general, we can not know when the user entered the queue, is generally in the queues, it should be able to out of the queue, but if the user is in the empty queue, the previous recursive call Dequeue execution is finished, you come in need to perform the operation of the queue.
So the code should look like this:
varQ =NewQueue (); functionA () {Console.log ("A was executed",NewDate ()); } functionB () {Console.log ("B executed",NewDate ()); } functionC () {Console.log ("C was executed",NewDate ()); } functiond () {Console.log ("D carried out",NewDate ()); } q.wait (2000); Q.queue (a); if(!q.isdequeue) {q.dequeue (); } q.wait (2000); Q.queue (b); if(!q.isdequeue) {q.dequeue (); } setTimeout (function() {//3S came in later.Q.wait (2000); Q.queue (c); if(!q.isdequeue) {q.dequeue (); } }, 3000); SetTimeout (function() {//8S came in later.Q.wait (2000); Q.queue (d); if(!q.isdequeue) {q.dequeue (); } }, 8000);
In this way, every time you enter a queue, it is OK to decide whether to go out of the queue.
JS Asynchronous function queue