

/**
 * 重复指定次数，然后结束。
 */
export default class Repeater {
  private onRepeat: Function;
  private onEnd: Function;
  private count: number;
  private duration: number;
  private interval = null;
  constructor(onRepeat: Function, onEnd: Function, count: number = 6, duration: number = 500) {
    this.onRepeat = onRepeat;
    this.onEnd = onEnd;
    this.count = count;
    this.duration = duration;
  }

  start() {
    if (this.interval) { this.cancel(); }

    let _count = 0;
    this.interval = setInterval(() => {
      if (_count < this.count) {
        _count++;
        this.onRepeat(_count);
      } else {
        this.cancel();
      }
    }, this.duration)
    return this;
  }

  cancel() {
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
      this.onEnd();
    }
    return this;
  }


}

