如何在代码运行时判判定时器的状态

参考:https://stackoverflow.com/que...this

问题:当前模块只须要一个定时器。可是若是有多个地方调用getData()会出现多个定时器code

private timer = null;
  private setTimer() {
      this.timer = setTimeout(function () {
        this.getData();
      }.bind(this), 5000);
  }

  getData() {
    http.get('getxxxData', () => {
      //....
      this.setTimer();
    });
  }

解决方法:在启动新的定时器以前判断上一个定时器是否正在运行,若是正在运行,就清除正在进行的定时器,再从新开启定时器。 但遗憾的是, 除了启动或中止计时器以外,没有其余方法能够与计时器交互。get

在启动定时器以前检测若是定时器不为null,须要清除定时器
  private timer = null;
  private clearPollTimer() {
    window.clearTimeout(this.timer);
    this.timer = null;
  }

  private setTimer() {
      if (this.timer !== null) {
        this.clearPollTimer();
      }
      this.timer = setTimeout(function () {
        this.getData();
      }.bind(this), 5000);
  }

  getData() {
    http.get('xxxx', () => {
      //....
      this.setTimer();
    });
  }
相关文章
相关标签/搜索