export default function useLoop(action, interval) {
  let sts = [];
  let stoped = true;

  async function run() {
    clear();
    if (stoped) return;
    try {
      if (action instanceof Promise) {
        await action();
      } else {
        action();
      }
    } catch (error) {
      console.log(error);
    }

    if (stoped) return;
    sts.push(setTimeout(run, interval));
  }

  function start() {
    stoped = false;
    run();
  }

  function clear() {
    sts.forEach((st) => {
      clearTimeout(st);
    });
    sts = [];
  }

  function stop() {
    stoped = true;
    clear();
  }

  return {
    stoped,
    stop,
    start,
  };
}
