js實現一個任務隊列

function EventQueue(delayTime) {

  this._delayTime = delayTime || 20;

  this._queue = [];

  this._canRun = true

}

 

EventQueue.prototype = {

  add: function (fn, params) {

    this._queue.push({

      fn: fn,

      params: params

    });

    return this

  },

 

  start: function () {

    this._canRun = true

    if (this._delayTime <= 0) {

      this.run(true);

    } else {

      var self = this;

      setTimeout(function () {

        self.run(true);

      }, self._delayTime);

    }

  },

 

  run: function (start = false) {

    if(!this._canRun)return;

    var item = this._queue.shift();

    if (item) {

      this._canRun = false

      let self = this;

        item.fn(item.params, function () {

          if(start){

            self._canRun = true

            self.run(true)

            return self

          }

          self.run()

        })

      }

    return self

  },

  stop(){

    this._queue.unshift(null)

    return this

  },

  next:function(){

      this.run()

      return this

  }

};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章