问题描述:
直接用setInterval调接口,会导致一直不间断的调用,不管上次调用是否请求成功,有可能会导致程序报错。经过一个贵人讲解之后受益匪浅,记录一下。
如何解决这个问题?
用setTimeout模拟setInterval
//handleKLineSuccess表示当折线图初始化完成
handleKLineSuccess() {
//getFirstRealtime()调接口方法
this.getFirstRealtime().then(() => {
this.fetchDataPerMinute();
});
},
fetchDataPerMinute() {
setTimeout(() => {
//getDataRealtime()为封装好的调接口方法,略过
this.getDataRealtime().then(() => {
if (this.fetchDataTimer) { // 如果不关闭页面
this.fetchDataPerMinute();
}
});
}, 30000);
},
//fetchDataTimer字段来控制是否继续调用fetchDataPerMinute();
beforeDestroy() {
this.fetchDataTimer = false;
},
讲解运行步骤:
- 调用折线图初始化完成方法handleKLineSuccess()
- 调用接口方法getFirstRealtime()
- getFirstRealtime()请求成功之后,调用fetchDataPerMinute()方法
- 等待30秒
- 调用接口方法getDataRealtime()
- getDataRealtime()请求成功
- 再次等待30秒
- 继续调用getDataRealtime()接口方法
- 间隔30秒继续调…
- 当关闭页面时,即this.fetchDataTimer = false; 此时取消定时调用getDataRealtime()方法