函數(shù)節(jié)流
適用場景:按鈕防重復(fù)點擊
/**
* 函數(shù)節(jié)流 delay時間內(nèi),連續(xù)發(fā)起多個請求,只執(zhí)行第一個請求
* @param fun
* @param delay
* @returns {function()}
*/
const throttle = (fun, delay) => {
let last = null;
return (...cc) => {
const now = + new Date();
if (now - last > delay) {
fun(...cc);
last = now;
}
}
};
函數(shù)防抖
適用場景:input輸入框搜索
/**
* 函數(shù)防抖 delay時間內(nèi),連續(xù)發(fā)起多個請求,只執(zhí)行最后一個請求
* @params fun 需要防抖的方法
* @params delay 毫秒數(shù)
*/
const debounce = (fun, delay) => {
let timer = null;
return (...cc) => {
clearTimeout(timer);
timer = setTimeout(() => {
fun(...cc);
}, delay);
}
};