const { myInterval, clearMyInterval } = (function(){
// 存放系统中的定时器id
let timerIdMap = { num: 0 }
function myInterval(callback, interval) {
// 每设置一次定时器,num++ 代表系统中有num个自定义的定时器
timerIdMap.num ++
// 第 num 个定时器的id
let intervalId = 'id' + timerIdMap.num
timerIdMap[intervalId] = true;
// 循环次数
let count = 0
let startTime = Date.now();
let loop = () => {
// 系统map中不存在这个id,就停止循环
if (!timerIdMap[intervalId]) {
return
}
if (Date.now() > startTime + interval * (count + 1)) {
count++;
callback(count)
}
window.requestAnimationFrame(loop)
}
loop()
return intervalId
}
// 清空定时器,删除全局的定时器id map
function clearMyInterval(intervalId) {
delete timerIdMap[intervalId]
}
return {
myInterval,
clearMyInterval
}
}());
// 调用定时器方法,返回定时器id,用于按条件清空
let timerId = myInterval((count) => {
console.log(count)
fetch('xxxx',{
method:"post"
}).then(res => res.json()).then(res => {
if(res.code ===0 && count ==5){
clearMyInterval(timerId)
}
})
}, 2000)
// 调用定时器方法,返回定时器id,用于按条件清空
let timerId2 = myInterval((count) => {
if (count > 15) {
clearMyInterval(timerId2)
}
}, 1000)