class Timer {
constructor() {
this.timerArr = [];
this.timerAcc = 0;
this.timerCycle = 100;
this.timerFn = () => {
// 判断是否有轮询方法
if (this.timerArr.length) {
this.timerArr.forEach(({ FN, cycle }) => {
// FN是否为function, 且是否是到轮询周期
if (Object.prototype.toString.call(FN) === '[object Function]' && !(this.timerAcc % cycle)) {
FN();
}
});
this.timerAcc = this.timerAcc + 1 >= 12000 ? 0 : this.timerAcc + 1;
} else {
// 若没有轮询方法 清除定时器
clearInterval(this.timer);
this.timer = null;
}
};
this.timer = null;
}
add({ FN, ID, cycle }) {
// 生成唯一标识
const symbol = Symbol.for(ID + new Date().getTime());
this.timerArr.push({
FN,
symbol,
cycle,
});
// 若timer为空则重新创建定时器
if (!this.timer) this.timer = setInterval(this.timerFn, this.timerCycle);
return symbol;
}
remove({ symbol }) {
this.timerArr = this.timerArr.filter(item => item.symbol !== symbol);
}
}
const tim = new Timer();
export default tim;
实现了一个简单的工厂函数,不同的是,在文件的结尾,对外提供的是一个实例