当请求过于频繁的时候,可以使用防抖和节流。
防抖:在延迟时间内的多次触发中只会执行最后一次
节流:在指定的时间内只允许执行一次。
// 防抖(方法,毫秒)
Debounce(fn, delay) {
let timeoutId = null;
return function(...args) {
clearInterval(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, delay)
}
}
// 节流(方法,毫秒)
Throttle(fn, limit) {
let inThrottle;
return function(...args) {
const _self = this;
if (!inThrottle) {
fn.apply(_self, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
};
}
}