Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@AgneseLee
Copy link

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
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants