js异步函数队列
場(chǎng)景:
做直播,會(huì)有入場(chǎng)消息,入場(chǎng)特效,用戶如果有坐騎,需要給他展示幾秒鐘的坐騎特效,如果幾個(gè)人同時(shí)進(jìn)場(chǎng),那該怎么展示呢?這時(shí)候就會(huì)想到setTimeout函數(shù),對(duì),思路不錯(cuò),但是,異步函數(shù)隊(duì)列怎么實(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差不多同時(shí)進(jìn)來(lái);
c在a,b還沒完全出隊(duì)列的時(shí)候,進(jìn)來(lái)的;
d在a,b,c都除了隊(duì)列之后再進(jìn)來(lái)的。
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之后進(jìn)來(lái)的q.wait(2000);q.queue(c);},3000);setTimeout(function(){//8S之后進(jìn)來(lái)的q.wait(2000);q.queue(d);q.dequeue();},8000);這里我們就需要判斷什么時(shí)候要調(diào)用dequeue來(lái)出隊(duì)列了。(為什么c進(jìn)隊(duì)列的時(shí)候,不需要dequeue,但是d進(jìn)來(lái)的時(shí)候就需要dequeue了呢?)
但是一般我們是無(wú)法知道用戶什么時(shí)候進(jìn)場(chǎng)的,一般都是進(jìn)隊(duì)列了,就該能出隊(duì)列,但是如果用戶是在空隊(duì)列的時(shí)候進(jìn)來(lái)的,之前的遞歸調(diào)用dequeue就執(zhí)行完了,你進(jìn)來(lái)需要再執(zhí)行 出隊(duì)列的操作。
于是,代碼應(yīng)該這樣:
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之后進(jìn)來(lái)的q.wait(2000);q.queue(c);if (!q.isdequeue) {q.dequeue();}}, 3000);setTimeout(function() { //8S之后進(jìn)來(lái)的q.wait(2000);q.queue(d);if (!q.isdequeue) {q.dequeue();}}, 8000);這樣,每進(jìn)一次隊(duì)列,就判斷要不要出隊(duì)列,事情就OK了。
轉(zhuǎn)載于:https://www.cnblogs.com/MissFelicia/p/6650396.html
總結(jié)
- 上一篇: mysql 优化配置参数(my.cnf)
- 下一篇: RPC-非阻塞通信下的同步API实现原理