import { onUnmounted } from "vue";

/**
 * 自动添加和清除timer
 */
export function useTimers() {
  const mixin__intervals: number[] = [];
  const mixin__timeouts: number[] = [];

  /**
   * 会在 beforeDestory 中自动清除
   * @param {function} fn 要执行的函数
   * @param {number} interval 执行间隔ms
   */
  // eslint-disable-next-line @typescript-eslint/ban-types
  function addInterval(fn: Function, interval: number) {
    const i = setInterval(fn, interval);
    mixin__intervals.push(i);
  }
  /**
   * 会在 beforeDestory 中自动清除
   * @param {function} fn 要执行的函数
   * @param {number} timeout 触发时间ms
   */
  // eslint-disable-next-line @typescript-eslint/ban-types
  function addTimeout(fn: Function, timeout: number) {
    const i = setTimeout(fn, timeout);
    mixin__timeouts.push(i);
  }

  onUnmounted(() => {
    for (const i of mixin__intervals) {
      clearInterval(i);
    }
    for (const i of mixin__timeouts) {
      clearTimeout(i);
    }
  });

  return {
    addInterval,
    addTimeout,
  };
}
