一:防抖
防抖和节流都是通过setTimeout进行延迟执行的机制;具体说明如下:
原理:
- 防抖分为两种情况:
- 第一种是:第一次点击触发回调函数,之后再 time 时间之内都不触发函数的回调(比如上拉刷新...)
- 第二种是:第一次不触发,在time时间之内触发的函数都不执行,在最后一次事件执行的 time 时间之后调用
// 防抖
function debounce (fn, time = 1000, triggerNow) {
var t = null,
res;
var debounced = function () {
const _self = this
const args = arguments
// 先立即执行
if (triggerNow) {
const exits = t
if (t) {
clearTimeout(t)
}
t = setTimeout(() => {
t = null
}, time)
if (!exits) {
res = fn.apply(_self, args)
}
} else {
clearTimeout(t)
t = setTimeout(() => {
res = fn.apply(_self, args)
}, time)
}
return res
}
// 强制取消防抖
debounced.remove = function () {
clearTimeout(t)
t = null
}
return debounced
},
二:节流
原理:
通过第一次函数调用的时间(sTime),和事件函数执行时间(eTime)相比较
- 通过 delay 设置的延迟时间,连续触发事件,回调只在 delay 时间之内触发一次;
- 最后一次事件,将会在 delay 时间之后执行
// 节流
function throttle (fn, delay = 1000) {
var t = null,
// 记录开始时间和结束时间作比较
begain = new Date().getTime()
// 返回一个函数,通过监听事件进行调用
return function () {
// 清除定时器
clearTimeout(t)
// 记录事件函数调用的时间
var cur = new Date().getTime(),
_self = this,
args = arguments
// 事件执行事件差,和延迟时间相比较
if (cur - begain >= delay) {
fn.apply(this, args)
begain = cur
} else {
// 最后一次 事件 delay 执行回调
t = setTimeout(function () {
fn.apply(_self, args)
begain = cur
}, delay)
}
}
},