最近在编写飞机大战,开发到一半想到 是否可以选择暂停游戏 常见的清理就是用 clearTimerout
或者 clearInterval
那么 如果数量多了 就会出现有些定时器没有清理的问题 为了避免出现这些问题出现 我尝试封装了一下定时器 代码如下:
class Interval {
constructor(delayTimer) {
this.intervalTimer = null;
this.intervalFuncMap = {};
this.intervalDelay = delayTimer;
}
// 创建定时器
createInterval() {
this.clearInterval();
this.intervalTimer = setInterval(() => {
this.intervalOperationFunc();
}, this.intervalDelay);
}
// 清除定时器
clearInterval() {
if (this.intervalTimer) {
clearInterval(this.intervalTimer);
this.intervalTimer = null;
}
}
// 重新设置定时器的间隔时间
setIntervalDelay(delay) {
this.intervalDelay = delay;
this.clearInterval();
this.createInterval();
}
// 添加
add(func, id) {
if (this.hasOwnProperty(id)) {
this.remove(id);
}
this.intervalFuncMap[id] = func;
return true;
}
// 是否存在
hasOwnProperty(id) {
return this.intervalFuncMap.hasOwnProperty(id);
}
// 删除
remove(id) {
return delete this.intervalFuncMap[id];
}
// 执行定期函数
intervalOperationFunc() {
const intervalFuncMap = this.intervalFuncMap;
for (const key in intervalFuncMap) {
const func = intervalFuncMap[key];
if (typeof func === "function") {
func();
}
}
}
}
// 初始化定时器时间
const intervalStore = new Interval(1000);
intervalStore.createInterval();
说明一下我的使用环境:
- 1.暂停采用清理定时器,基本上都是一样的
- 2.定期可以执行函数
- 3.通过id可以移除函数
- 4.使用方便
- 5.暂停不会清空添加当中的函数
**
添加定期执行函数
**
// 使用起来很简单 和平常的函数一样 只需要记录唯一id即可
intervalStore.add(() => {
....
}, id);
删除函数
// 移除定时执行的函数 采用唯一id
intervalStore.remove(id);
暂停全局定时器
// 只需要调用一次 全局定时器将会进行清空, 但是不会移除已经记录的函数
intervalStore.clearInterval();
继续执行全局定时器
// 继续执行全局定时器
intervalStore.createInterval();
全局计时器改变速度
// 只需要调用函数 将会重新刷新定时器 并且更改时间
intervalStore.setIntervalDelay(2000);
这只是当中一个方法 完整飞机大战项目可以查看:https://github.com/SDSGK/plane-ES6