YvonneZhang
3/2/2016 - 8:36 AM

Loop.js

Loop.js

/**
 * @example
 * const loop = new Loop({
 *    before: ()=> {
 *      console.log('before');
 *    },
 *    repeat: ()=> {
 *      console.log('repeat');
 *    },
 *    after: ()=> {
 *      console.log('end');
 *    }
 * }, 3, 3);
 * loop.activate();
 */

class Loop {
  /**
   * 轮询
   * @param {object} 动作集合:
   *  {
   *    @param {function} before 运行之前
   *    @param {function} repeat 重复动作
   *    @param {function} after  运行之后
   *    @param {function} stop   终止条件
   *  }
   * @param {number || Number.POSITIVE_INFINITY} count    重复次数
   * @param {number} interval 间隔时间(s)
   */
  constructor({before = (()=>null), repeat = (()=>null), after = (()=>null), stop = (()=>null)}, count = Number.POSITIVE_INFINITY, interval = 3) {

    this.before = before;
    this.repeat = repeat;
    this.after = after;
    this.stop = stop;

    this.interval = interval * 1000;
    this.count = count;

    this.once = {
      before: true,
      after: true
    };
  }

  beforeAction() {
    if (this.once.before) {
      this.before();
      this.once.before = false;
    }
  }

  repeatAction() {
    if (this.count > 0) {
      this.repeat();
      this.timer = setTimeout(function () {
        this.activate();
      }.bind(this), this.interval);
      if (this.count !== Number.POSITIVE_INFINITY) {
        this.count--;
      }
    }
  }

  afterAction() {
    if (this.count === 0 && this.once.after) {
      this.after();
      this.once.after = false;
    }
  }

  activate() {
    clearTimeout(this.timer);
    if (this.stop()) {
      return;
    }
    this.beforeAction();
    this.repeatAction();
    this.afterAction();
  }
}