函數節流
適用場景:按鈕防重復點擊
/**
* 函數節流 delay時間內,連續發起多個請求,只執行第一個請求
* @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;
}
}
};
函數防抖
適用場景:input輸入框搜索
/**
* 函數防抖 delay時間內,連續發起多個請求,只執行最后一個請求
* @params fun 需要防抖的方法
* @params delay 毫秒數
*/
const debounce = (fun, delay) => {
let timer = null;
return (...cc) => {
clearTimeout(timer);
timer = setTimeout(() => {
fun(...cc);
}, delay);
}
};