计时器统一管理,es6 class写法
let PRIVSTATE;//key for setInterval
class Timer {
/*
* key construct
* {
* key:String//该计时器标识符
* call:fn,//回调函数
* delay:Num,//时间间隔,单位为秒
* params:[]//回调函数参数
* }
*/
static keys = [];
//初始化状态interval-key
// static PRIVSTATE = null;
static init() {
if (!PRIVSTATE && this.keys.length) {
PRIVSTATE = window.setInterval(() => {
this.keys.map(item => {//遍历计时器队列
if (item) {
let {
call,
delay,
params
} = item;
delay = delay ? parseInt(delay) : 1;
if(!item.delay_count){
item.delay_count = delay;
}
item.delay_count--;
if (item.delay_count <= 0) {//计算间隔时间
item.delay_count = delay;
if (params && params.length) {
call && call(...params);
} else {
call && call();
}
}
}
})
}, 1000);
}
};
static setIn(...rest) {
let callObj = {};
for(var o of rest){//参数获取
switch (Object.prototype.toString.call(o)) {
case "[object Array]":
callObj.params = o;
break;
case "[object String]":
callObj.key = o;
break;
case "[object Number]":
callObj.delay = o;
break;
case "[object Function]":
callObj.call = o;
break;
default:
console.log('noValide param')
break;
}
}
if(callObj.call){
if(!callObj.key){
console.log(callObj.call.name);
callObj.key = callObj.call.name;
}
let itemIn = this.keys.findIndex(item => item.key && item.key === callObj.key);
if (itemIn >= 0) {//插入队列
this.keys[itemIn] = callObj;
} else {
this.keys.push(callObj);
}
this.init();
}
};
static cleanIn(key) {//String//清除计时器
if (key) {
let itemIn = this.keys.findIndex(item => item.key && item.key === key);
if (itemIn >= 0) {
this.keys.splice(itemIn, 1);//删除队列项
} else {
console.error('no Key');
}
}else{
//TODO clean All
this.keys = [];//清除队列
}
if (!this.keys.length && PRIVSTATE) {
window.clearInterval(PRIVSTATE);
PRIVSTATE = null;
}
}
};
export default Timer;
调用
import timer from './timer.js'
timer.setIn(handleFn,2,'timeSet')
timer.cleanIn('timeSet')//清除timeSet
timer.cleanIn()//清除所有计时器
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。