Vue 防抖与节流
防抖
高频请求只有最后一次处理
实现原理:每次响应时清空定时期,延时时间要高于高频请求的间隔
function debounce(fn, delay = 500) {
let timer = null
return function() {
let args = arguments
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args);
}, delay)
}
}
核心就是调用时需要注意,利用的是闭包,method需要赋予执行后的返回值
antiShake: debounce(function() {
console.log('前辈会被清除吗?2')
}, 1000),
antiShake2: debounce(function() {
console.log('兄弟会被清除吗?1')
}),
// 请勿使用箭头函数,它没有this
可在created中测试
this.antiShake()
this.antiShake()
this.antiShake()
this.antiShake2()
this.antiShake2()
this.antiShake2()
// 兄弟会被清除吗?1
// 前辈会被清除吗?2
节流
每处理一次请求,会有一段时间的静默
export function throttle(fn, interval = 500) {
var last;
return function () {
var args = arguments;
var now = +new Date();
if (!last || now - last > interval) {
last = now;
fn.apply(this, args);
}
}
}
内容会不断更新,欢迎批评指正。

浙公网安备 33010602011771号