接手了个老项目,别的模块有定时器在后面跑,特殊情况是需要在当前的模块下给它结束掉,但是苦于不知道定时器的码;
暴力清理全局定时器
// 清理所有未知定时器
export function ClearGlobalUnknownTimer() {
let end: any = setTimeout(() => {}, 1000);
for (let i = 1; i <= end; i++) {
clearInterval(i);
clearTimeout(i);
}
}
理性清理全局定时器
// 定时器管理
/* 项目中版本: "storejs": "^2.0.1" */
import storejs from 'storejs'
// 存入全局定时器num
export function SetGlobalTimerNum(timeNum: any) {
let tmpList = GetGlobalTimerNum();
tmpList.push(timeNum);
storejs.set('GLOBAL_TIMER_LIST', tmpList);
};
// 读取全局定时器num
export function GetGlobalTimerNum() {
return storejs.get('GLOBAL_TIMER_LIST') || [];
};
export function ClearSingleGlobalTimer(timeNum: any) { // 删除单个
let tmpList = GetGlobalTimerNum();
if (tmpList.includes(timeNum)) {
tmpList.splice(tmpList.indexOf(timeNum), 1);
storejs.set('Az_GLOBAL_TIMER_LIST', tmpList);
}
};
export function ClearGlobalTimerNum() { // 清空现有定时器并置空
let timerNum = GetGlobalTimerNum();
if (timerNum.length === 0) {return;};
for (let i in timerNum) {
if (typeof timerNum[i] === 'number') {
clearInterval(timerNum[i]);
clearTimeout(timerNum[i]);
}
};
RemoveGlobalTimerNum();
};
export function RemoveGlobalTimerNum() { // 直接在本地存储中删除
storejs.remove('GLOBAL_TIMER_LIST');
};