防抖:
ajax提交应第一次不延迟(下拉刷新),输入应第一次就需要延迟
1.就是事件被触发n秒后再执行的回调 -> 延迟执行
2.如果在n面内再次被触发,重新开始计时
3.n秒内只要你触发事件,就重新计时,事件处理函数的程序就永远不能被执行
export function throttle(fn, delay, triggleNow) {
let bol = true
begin = 0
return function() {
let _this = this
args = arguments
cur = new Date().getTime()
if (triggleNow) {
if (cur - begin >= delay) {
fn.apply(_this, args)
begin = cur
}
} else {
if (bol) {
bol = false
t = setTimeout(() => {
fn.apply(_this, args)
bol = true
}, delay)
}
}
}
}
节流:
事件被触发,n秒之内值执行一次事件处理函数
export function debounce(fn, time, triggleNow) {
let t = null
let debounced = function() {
let args = arguments
if (t) {
clearTimeout(t)
}
if (triggleNow) {
let exec = !t
t = setTimeout(function() {
t = null
}, time)
if (exec) {
fn.apply(this, args)
}
} else {
t = setTimeout(function() {
fn.apply(this, args)
}, time)
}
}
debounced.remove = function() {
clearTimeout(t)
t = null
}
return debounced
}