函数截流是什么,手动实现一个截流函数

防抖截流

  • 原理:规定在单位时间内只能触发一次的函数。如果这个单位时间内触发多次函数,但是只执行一次。
  • 应用场景:
    • 拖拽场景:固定时间内只执行一次,防止高频触发位置变动;
    • 缩放场景:监控浏览器resize;

时间戳实现方式

  • 用当前执行的时间戳减去上一次执行时候的时间戳,如果大于设置的等待时间,就执行,反之,就不执行。
1
2
3
4
5
6
7
8
9
10
11
12
let throttle = (fun, wait) => {
let context, args, previous = 0
return () {
let now = +new Date()
context = this
args = arguments
if (now - previous > wait) {
fun.apply(context, args)
previous = now
}
}
}

使用定时器方式

  • 可以通过出发定时器来实现,如果定时器存在就不执行,反之,就执行。
1
2
3
4
5
6
7
8
9
10
11
let throttle = (fun, wait) {
let timer
return function () {
let context = this
let args = arguments
timer = setTimeout(function () {
timer = null
fun.apply(context, args)
}, wait)
}
}

that’s all!

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

请我喝杯咖啡吧~

支付宝
微信