場景:
做直播,會有入場消息,入場特效,用戶如果有坐騎,需要給他展示幾秒鍾的坐騎特效,如果幾個人同時進場,那該怎么展示呢?這時候就會想到setTimeout函數,對,思路不錯,但是,異步函數隊列怎么實現呢?直接上代碼:
var Queue = 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() { var self = this, list = self.list; self.isdequeue = true; var el = list.shift() || function() {}; if (typeof el == "number") { setTimeout(function() { self.dequeue(); }, el); } else if (typeof el == "function") { el.call(this) if (list.length) { self.dequeue(); } else { self.isdequeue = false; } } } };
例子:
如果a,b差不多同時進來;
c在a,b還沒完全出隊列的時候,進來的;
d在a,b,c都除了隊列之后再進來的。
var q = new Queue(); function a() { console.log("a執行了", new Date()); } function b() { console.log("b執行了", new Date()); } function c() { console.log("c執行了", new Date()); } function d() { console.log("d執行了", new Date()); } q.wait(2000); q.queue(a); q.wait(2000); q.queue(b); q.dequeue(); setTimeout(function(){//3S之后進來的 q.wait(2000); q.queue(c); },3000); setTimeout(function(){//8S之后進來的 q.wait(2000); q.queue(d); q.dequeue(); },8000);
這里我們就需要判斷什么時候要調用dequeue來出隊列了。(為什么c進隊列的時候,不需要dequeue,但是d進來的時候就需要dequeue了呢?)
但是一般我們是無法知道用戶什么時候進場的,一般都是進隊列了,就該能出隊列,但是如果用戶是在空隊列的時候進來的,之前的遞歸調用dequeue就執行完了,你進來需要再執行 出隊列的操作。
於是,代碼應該這樣:
var q = new Queue(); function a() { console.log("a執行了", new Date()); } function b() { console.log("b執行了", new Date()); } function c() { console.log("c執行了", new Date()); } function d() { console.log("d執行了", new Date()); } 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之后進來的 q.wait(2000); q.queue(c); if (!q.isdequeue) { q.dequeue(); } }, 3000); setTimeout(function() { //8S之后進來的 q.wait(2000); q.queue(d); if (!q.isdequeue) { q.dequeue(); } }, 8000);
這樣,每進一次隊列,就判斷要不要出隊列,事情就OK了。