防抖与节流
防抖:高频事件只执行最后一次
// 简易版防抖
function debounce (fn, wait = 500) {
let timeOut = null;
return function (...args) {
if (timeOut) clearTimeout(timeOut);
timeOut = setTimeout(() => {
fn.call(this, ...args);
}, wait);
}
}
节流:一段时间之内只执行一次
// 简易版节流
function throttle (fn, wait = 500) {
let flag = null;
return function (...args) {
if (!flag) {
flag = true;
setTimeout(() => {
flag = false;
fn.call(this, ...args);
}, wait);
}
}
}