节流函数

概念解读
函数节流是指一定时间内js方法只跑一次。生活例子:人的眨眼睛,就是一定时间内眨一次。
应用场景:
1、鼠标不断点击触发,mousedown(单位时间内只触发一次)。2、监听滚动事件(它是一个高频触发对事件),比如是否滑到底部自动加载更多,用throttle来判断。
函数:
function throttle(fun, delay) {
let last, deferTimer
return function (args) {
let that = this
let _args = arguments
let now = +new Date()
if (last && now < last + delay) {
clearTimeout(deferTimer)
deferTimer = setTimeout(function () {
last = now
fun.apply(that, _args)
}, delay)
}else {
last = now
fun.apply(that,_args)
}
}
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理