Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b 的时间,然后写一个 myClear,停止上面的 mySetInterVal

Sunny-117 opened this issue · comments

写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b 的时间,然后写一个 myClear,停止上面的 mySetInterVal
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);

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)