一、在切换页面时关闭/启动计时器
const timer = setInterval(() => {
// 切换页面关计时器
if (document.getElementById("main") === null) {
window.clearInterval(timer);
return;
}
this.getProgress(batchNo, codes)
}, 1000);
二、不刷新页面的情况下,自如的开启关闭定时器
左侧树选择后,进度条progressNum要重置0
进度条值为100%时
按钮代码:
场景逻辑:
1、左侧树选区划,点按钮,然后调用获取批次号的接口
注意:每次选区划的时候,进度条progressNum要重置0
2、以区划代码和批次号为入参,调用获取进度条值的接口,进度条值的接口每秒刷新1次
注意:在progressNum为100时,要停止每秒调接口。
代码:
/** 获取五码编写批次号 */
getBatchNo = async () => {
const { regionCodes, progressNum } = this.state;
if (regionCodes && regionCodes.length > 0) {
const result = await
DatabaseManageProvider.getCompile(regionCodes.toString())
this.setState({
batchNo: result,
}, async () => {
// !!!开启计时器,并1S刷新获取进度值progressNum的接口
this.timerStart(result, regionCodes);
})
}
};
/** 获取进度*/
getProgress = async (batchNo: string, codes: string[]) => {
// 调用获取进度条值progressNum接口之前,先判断进度值progressNum如果100,则调用关闭计时器的方法
if (this.state.progressNum === 100) {
this.timerEnd();
}
if (codes && codes.length > 0) {
const params = {
regionCodes: codes.toString(),
batchNo,
}
const num = await DatabaseManageProvider.getProgress({ ...params });
this.setState({
progressNum: +num,
});
}
};
!!!!最重要的开启和关闭计时器的方法
timerList是长度为1的数组
state: State = {
batchNo: "",
progressNum: 0,
slTableNames: [],
sxTableNames: [],
open: false,
};
timerList: number[] = [];
timer = 0;
/** 计时器open*/
timerStart = (batchNo: string, codes: string[]) => {
const timer = setInterval(() => { this.getProgress(batchNo, codes) }, 1000);
// 计时器调用一侧会有一个ID,需要记录存在全局timerList里,timerList是一个长度为1的数组,比如:[27]
this.timerList.push(timer)
}
/** 计时器close */
timerEnd = () => {
// console.log("关闭");
// 挨个遍历timerList,挨个关闭
console.log(this.timerList, "this.timerList--->");//[24]
this.timerList.forEach((item, index) => {
clearInterval(item);
})
this.timerList = []
this.timer = 0;
}