题目:
写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b,…,a+nb 的时间,然后写一个 myClear,停止上面的 mySetInterVal
解答:
function mySetInterval(fn, a, b) {
this.a = a;
this.b = b;
this.time = 0;
this.handler = null;
this.start = () => {
this.handler = setTimeout(() => {
console.log(this.a + this.time * this.b);
fn();
this.start();
this.time++;
}, this.a + this.time * this.b);
};
this.stop = () => {
if (this.handler) {
clearTimeout(this.handler);
}
this.time = 0;
};
}
const a = new mySetInterval(() => console.log(new Date().getTime()), 1000, 2000);
a.start();
a.stop();
有好的解答,可以写在下方。
喜欢可以给个赞,共同进步。
参考github,一起学习