永康嘉持电器有限公司前端
小小儁爺
2024-12-30 ff2f7d7bad0132c130c305364a863ff446e926b2
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 节流是指:让其在第一次触发事件
// 防抖是指:让其在最后一次触发事件
 
// fn对应的时间处理函数,delay间隔时间,immediate第一次是否立即执行
// 防抖
const debounce = function(fn, delay, immediate) {
  let timer = null
  return function() {
    const that = this
    const arg = arguments
    if (timer) {
      clearTimeout(timer)
    }
    if (immediate) {
      const bool = !timer
      timer = setTimeout(() => {
        timer = null
      }, delay)
      if (bool) {
        fn.apply(that, arg)
      }
    } else {
      timer = setTimeout(() => {
        timer = null
        fn.apply(that, arg)
      }, delay)
    }
  }
}
 
// 节流
const throttle = function(fn, delay, immediate) {
  let timer = null
  return function() {
    const that = this
    const arg = arguments
    if (immediate) {
      if (!timer) {
        timer = setTimeout(() => {
          timer = null
        }, delay)
        fn.apply(that, arg)
      }
    } else {
      if (!timer) {
        timer = setTimeout(() => {
          timer = null
          fn.apply(that, arg)
        }, delay)
      }
    }
  }
}
 
export { debounce, throttle }