函数节流(throttle)

节流: 让函数有节制地执行,而不是毫无节制的触发一次就执行一次。什么叫有节制呢?就是在一段时间内,只执行一次

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 节流函数
* @param {Function} fun 需要节流的函数
* @param {Number} delay 间隔触发的时间
* @returns
*/
function throttle(fun, delay) {
let flag = true, timer = null
return function (...args) {
let context = this
if (!flag) {
return
}
flag = false
clearTimeout(timer)
timer = setTimeout(() => {
fun.apply(context, args)
flag = true
}, delay)
}
}

场景:

  • 鼠标的点击事件
  • 监听滚动事件

函数防抖(debounce)

防抖: 在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

代码:

1
2
3
4
5
6
7
8
9
10
function debounce(fun, delay) {
let timer = null
return (...args) => {
if(timer) clearTimeout(timer)
timer = setTimeout(() => {
fun.apply(this, args)
timer = null
})
}
}

场景:

  • 搜索框提示
  • 调整窗口大小
  • 防止多次表单提交