import { ref } from "vue";

type ActionFunc = () => Promise<unknown>;

export default function useLoop(action: ActionFunc, interval: number) {
  let sts: NodeJS.Timeout[] = [];
  const stoped = ref(true);

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

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

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

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

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

  return {
    stoped,
    stop,
    start,
  };
}
