国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

JS異步函數(shù)隊列功能實例分析

2024-05-06 15:23:58
字體:
供稿:網(wǎng)友

本文實例講述了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);            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 自治县| 台安县| 牙克石市| 永靖县| 石渠县| 弋阳县| 思南县| 呼和浩特市| 昭苏县| 云梦县| 郴州市| 盐边县| 苍溪县| 泰州市| 乐陵市| 淮南市| 安平县| 中卫市| 沧源| 奉新县| 淮北市| 麻栗坡县| 汉源县| 鹤岗市| 丰顺县| 太原市| 通榆县| 江门市| 普洱| 哈巴河县| 广西| 江门市| 夏津县| 宁波市| 高平市| 乳源| 长宁区| 田东县| 调兵山市| 麻江县| 阿拉善左旗|