li.shaoyi 3 年之前
父節點
當前提交
38f34b673f
共有 1 個文件被更改,包括 9 次插入9 次删除
  1. 9 9
      src/utils/timer/index.ts

+ 9 - 9
src/utils/timer/index.ts

@@ -106,7 +106,7 @@ export const timerTask = new (class {
  */
 export const timerInterceptor = new (class {
     private debounceMap = new Map<string, number>();
-    private throttleMap = new Map<string, number>();
+    private throttleMap = new Map<string, () => void>();
 
     /**
      * 函数防抖(等待触发)
@@ -135,8 +135,8 @@ export const timerInterceptor = new (class {
         return function (...args: T) {
             if (timer === 0) {
                 timer = window.setTimeout(() => {
-                    timer = 0;
                     callback(...args);
+                    timer = 0;
                 }, delay)
             }
         }
@@ -155,8 +155,8 @@ export const timerInterceptor = new (class {
         }
 
         const timer = window.setTimeout(() => {
-            this.debounceMap.delete(timerId);
             callback();
+            this.debounceMap.delete(timerId);
         }, delay)
 
         this.debounceMap.set(timerId, timer);
@@ -171,16 +171,16 @@ export const timerInterceptor = new (class {
      */
     throttle(callback: () => void, delay = 100, timerId = 'timer') {
         if (this.throttleMap.has(timerId)) {
-            const t = this.throttleMap.get(timerId);
-            if (t) return;
+            this.throttleMap.set(timerId, callback); // 更新最新函数
+            return;
         }
 
-        let timer = window.setTimeout(() => {
-            timer = 0;
+        window.setTimeout(() => {
+            const fn = this.throttleMap.get(timerId);
+            fn && fn();
             this.throttleMap.delete(timerId);
-            callback();
         }, delay)
 
-        this.throttleMap.set(timerId, timer);
+        this.throttleMap.set(timerId, callback);
     }
 })