写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b 的时间,然后写一个 myClear,停止上面的 mySetInterVal
Sunny-117 opened this issue · 2 comments
Sunny-117 commented
写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b 的时间,然后写一个 myClear,停止上面的 mySetInterVal
AgneseLee commented
function mySetInterVal(fn, a, b) {
let clear = false;
const intervalFn = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
fn();
if (clear) resolve(new Promise(() => {}));
else {
resolve(intervalFn());
}
}, b);
});
};
setTimeout(intervalFn, a);
return () => {
clear = true;
};
}
function myClear() {
clearTimeout(timerId);
}
const stoop = mySetInterVal(
() => {
console.log(Date.now());
},
1000,
2000
);
setTimeout(() => {
stoop();
}, 2000);
wongfugui commented
function mySetInterVal(fn, a, b) {
const handler = {
stop: false,
timer: null
}
const loop = n => {
if (handler.stop) {
return
}
handler.timer = setTimeout(() => {
fn()
loop(n + 1)
}, (a + n * b) * 1000)
}
loop(0)
return handler
}
function myClear(handler) {
handler.timer && clearTimeout(handler.timer)
handler.stop = true
}
const timer = mySetInterVal(() => console.log(new Date()), 1, 2)
myClear(timer)