Browse Source

refactor(工具类): 修正节流防抖函数并增加防抖功能

- 将 CertManager 中的 debounceHold 方法替换为 throttleHold 方法
- 修正 ToolsHelper 中的 throttleHold 方法实现
- 新增 ToolsHelper 中的 debounceHold 方法实现
徐勤民 2 days ago
parent
commit
7753f8ae52
1 changed files with 31 additions and 2 deletions
  1. 31 2
      src/main/ets/utils/ToolsHelper.ets

+ 31 - 2
src/main/ets/utils/ToolsHelper.ets

@@ -351,7 +351,7 @@ export class ToolsHelper {
       new AlertBean({
         title: options.title,
         msg: options.msg,
-        cancel: options.cancel??{},
+        cancel: options.cancel ?? {},
         confirm: options.confirm
       }, dialogTag))
     ui.getPromptAction().openCustomDialog(c, {
@@ -546,7 +546,7 @@ export class ToolsHelper {
    * @param fun
    * @param wait
    */
-  static debounceHold(fun: Function, wait: number = 1500) {
+  static throttleHold(fun: Function, wait: number = 1500) {
     let funcValue1 = ToolsHelper.getUniqueId(fun)
     let hash = md5_hex(funcValue1)
     if (ToolsHelper.setTimeOutMap.get(hash)) {
@@ -568,6 +568,35 @@ export class ToolsHelper {
 
   }
 
+  /**
+   * 防抖函数(调用会立即触发,在wait时间内不再触发)
+   * @param fun
+   * @param wait
+   */
+  static debounceHold(fun: Function, wait: number = 1500) {
+    let funcValue1 = ToolsHelper.getUniqueId(fun)
+    let hash = md5_hex(funcValue1)
+    const func = ToolsHelper.setTimeOutMap.get(hash)
+    if (func) {
+      if (func.startTime + func.timeoutNumber <= new Date().getTime()) {
+        ToolsHelper.setTimeOutMap.delete(hash)
+      } else {
+        return
+      }
+    }
+    ToolsHelper.setTimeOutMap.set(hash, {
+      timeoutNumber: wait,
+      startTime: new Date().getTime(),
+    })
+    // 执行函数调用
+    fun()
+    // 拦截在wait期间的函数再次调用,在超时后,将限制解除
+    setTimeout(() => {
+      ToolsHelper.setTimeOutMap.get(hash) && clearTimeout(ToolsHelper.setTimeOutMap.get(hash)?.timeoutNumber)
+      ToolsHelper.setTimeOutMap.delete(hash)
+    }, wait)
+  }
+
   static toString(arrayBuffer: ArrayBuffer) {
     let decoder = util.TextDecoder.create('utf-8');
     return decoder.decodeToString(new Uint8Array(arrayBuffer))