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

问题:当前模块只需要一个定时器。但是如果有多个地方调用getData()会出现多个定时器

  private timer = null;  private setTimer() {      this.timer = setTimeout(function () {        this.getData();      }.bind(this), 5000);  }  getData() {    http.get('getxxxData', () => {      //....      this.setTimer();    });  }

解决方法:在启动新的定时器之前判断上一个定时器是否正在运行,如果正在运行,就清除正在进行的定时器,再重新开启定时器。 但遗憾的是, 除了启动或停止计时器之外,没有其他方法可以与计时器交互。

在启动定时器之前检测如果定时器不为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();    });  }