Michael Wang 3 gadi atpakaļ
vecāks
revīzija
5ac0039f2d
1 mainītis faili ar 44 papildinājumiem un 0 dzēšanām
  1. 44 0
      src/setups/useTimers.ts

+ 44 - 0
src/setups/useTimers.ts

@@ -0,0 +1,44 @@
+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,
+  };
+}