本文實例講述了JS異步函數(shù)隊列功能。分享給大家供大家參考,具體如下:
場景:
做直播,會有入場消息,入場特效,用戶如果有坐騎,需要給他展示幾秒鐘的坐騎特效,如果幾個人同時進場,那該怎么展示呢?這時候就會想到setTimeout函數(shù),對,思路不錯,但是,異步函數(shù)隊列怎么實現(xiàn)呢?直接上代碼:
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執(zhí)行了", new Date());}function b() { console.log("b執(zhí)行了", new Date());}function c() { console.log("c執(zhí)行了", new Date());}function d() { console.log("d執(zhí)行了", 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);這里我們就需要判斷什么時候要調(diào)用dequeue來出隊列了。(為什么c進隊列的時候,不需要dequeue,但是d進來的時候就需要dequeue了呢?)
但是一般我們是無法知道用戶什么時候進場的,一般都是進隊列了,就該能出隊列,但是如果用戶是在空隊列的時候進來的,之前的遞歸調(diào)用dequeue就執(zhí)行完了,你進來需要再執(zhí)行 出隊列的操作。
于是,代碼應該這樣:
var q = new Queue(); function a() { console.log("a執(zhí)行了", new Date()); } function b() { console.log("b執(zhí)行了", new Date()); } function c() { console.log("c執(zhí)行了", new Date()); } function d() { console.log("d執(zhí)行了", 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);
新聞熱點
疑難解答
圖片精選