JS非同步函數隊列功能執行個體分析,非同步執行個體分析

來源:互聯網
上載者:User

JS非同步函數隊列功能執行個體分析,非同步執行個體分析

本文執行個體講述了JS非同步函數隊列功能。分享給大家供大家參考,具體如下:

情境:

做直播,會有入場訊息,入場特效,使用者如果有坐騎,需要給他展示幾秒鐘的坐騎特效,如果幾個人同時進場,那該怎麼展示呢?這時候就會想到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了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.