# 前言

延迟后一次调用
常用案例:有一个搜索输入框,为了提升用户体验,希望在用户输入后可以立即展现搜索结果,而不是每次输入完后还要点击搜索按钮

# 实现

const debounce = function(func, wait = 0) {
  let timeout = null;
  let args;
  const debounced  = function(...arg) {
    args = arg;
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    return new Promise((resolve,reject) => {
      timeout = setTimeout(async () => {
        try {
          const result = await func.apply(this, args);
          resolve(result)
        } catch (e) {
          reject(e)
        }
      }, wait);
    })
    function cancel() {
      clearTimeout(timeout);
      timeout = null;
    }
    function flush() {
      cancel();
      return func.apply(this, args);
    }
    debounced.cancel = cancel;
    debounced.flush = flush;
    return debounced;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
最后更新时间: 6/20/2022, 10:48:50 PM