參考: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();
});
}