class Interval {
constructor() {
this.timeMap = {};
this.id = 0;
}
setInterval = (cb, time) => {
this.id++;
let fn = () => {
this.timeMap[this.id] = setTimeout(fn, time);
cb();
};
this.timeMap[this.id] = setTimeout(fn, time);
return this.id; // 返回 this.id
};
//改成这样就好了 但是不知道原理
_setInterval = (cb, time) => {
let timerId = this.id++;
let fn = () => {
this.timeMap[timerId] = setTimeout(fn, time);
cb();
};
this.timeMap[timerId] = setTimeout(fn, time);
return timerId; // 返回timeId
};
clearInterval = (id) => {
clearTimeout(this.timeMap[id]); // 通过timeMap[id]获取真正的id
delete this.timeMap[id];
};
}
let s = new Interval();
// 第一个定时器
let timer = s.setInterval(() => {
console.log('timer', timer);
}, 1000);
// 第二个定时器
let timer1 = s.setInterval(() => {
console.log('timer1', timer1);
}, 1000);
// 第三个定时器
let timer2 = s.setInterval(() => {
console.log('timer2', timer2);
}, 1000);
setTimeout(() => {
s.clearInterval(timer2); // !!!这里为什么只能清除最后一个定时器, 我传递 timer timer1 就无效
}, 2500);
参考 掘金
https://juejin.cn/post/684490...
刚开始认为 这个 this.id是 非引用类型,应该不会影响~
然后进一步想到 闭包 作用域的定义之类的,但是还是没有想明白.请各位看官 大佬 解读一番!
clearTimeout和setTimeout的实际顺序你稍微打印一下,你就不觉得你的cb时机不太对吗