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

export default function useLoop(action: ActionFunc, interval: number) {
  let st = null;
  let stoped = true;

  async function run() {
    if (stoped) return;
    await action().catch(() => {});

    if (stoped) return;
    st = setTimeout(run, interval);
  }

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

  function stop() {
    stoped = true;
    if (st) {
      clearTimeout(st);
      st = null;
    }
  }

  return {
    stoped,
    stop,
    start,
  };
}
