函数防抖是什么,手动实现一个防抖函数

防抖函数

  • 原理:在事件出发n秒之后再执行回调,如果在这n秒内再次触发,则重新开始计时。
  • 应用场景:
    • 按钮提交场景:防止多次点击按钮提交。只执行最后一次;
    • 搜索框连续输入场景:防止连续发送请求,只发送最后一次。

简易版:

1
2
3
4
5
6
7
8
9
10
11
let debounce = (fun, wait) => {
let timer
return function () {
const context = this
const args = arguments
clearTimeout(timer)
timeout = setTimeout(() => {
fun.apply(context, args)
}, wait)
}
}

立即执行

  • 立即触发,然后等到停止出发n秒后再次重新触发执行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let debounce = (fun, wait, immediate) => {
let timer
return function () {
const context = this
const args = arguments
if (timer) clearTimeout(timer)
if (immediate) {
const callNow = !timer
timer = setTimeout(function () {
timer = null
}, wait)
if (callNow) {
fun.apply(context, args)
}
} else {
timer = setTimeout(function () {
fun.apply(context, args)
}, wait)
}
}
}

有返回值

  • 某些情况下,fun可能会有返回值,所以需要返回函数的结果,但是当immediate为false的时候,因为使用了setTimeout,我们将fun.apply(context, args)的返回值赋值给变量,然后再return的时候,值将会一直undefined,所以只有immediate值为true的时候返回函数的执行结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let debounce = (fun, wait, immediate) => {
let timer, result
return function () {
const context = this
const args = arguments
if (timer) clearTimeout(timer)
if (immediate) {
const callNow = !timer
timer = setTimeout(function () {
timer = null
}, wait)
if (callNow) {
result = fun.apply(context, args)
}
} else {
timer = setTimeout(function () {
fun.apply(context, args)
}, wait)
}
return result
}
}

that’s all!

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2022 Lee
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信