节流和防抖是属于面试和日常开发过程中常见的问题
函数防抖(debounce)
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。用户在不断输入值时,用防抖来节约请求资源。
场景:监听input的每一次onkeyup事件请求,调用接口做模糊匹配。在频繁的输入中,如果每次都去调用接口,不仅会造成资源的浪费,而且在实际场景中,用户输入完成后再去请求。
export const debounce = (fn, delay) => {
let delays = delay || 200
let timer
return function () {
let th = this
let args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function () {
timer = null
fn.apply(th, args)
}, delays)
}
}
prevCheck: debounce(function () {
/*
* */
}, 800),
函数节流(throttle)
规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。
场景:列表页切换,请求接口返回列表数据。为了限制短时间内频繁请求大量列表数据,规定单位时间内才可以触发
export const throttle = (fn, t) => {
let last
let timer
let interval = t || 500
return function () {
let args = arguments
let now = +new Date()
if (last && now - last < interval) {
clearTimeout(timer)
timer = setTimeout(() => {
last = now
fn.apply(this, args)
}, interval)
} else {
last = now
fn.apply(this, args)
}
}
}
prevCheck: throttle(function () {
/*
* */
}, 800),