函數(shù)進階
函數(shù)防抖(debounce)以最后一次為準
解決辦法:延遲 n 秒執(zhí)行,只執(zhí)行 n 毫秒內(nèi)最后一次觸發(fā),提升執(zhí)行速度,避免接口過載,節(jié)省資源
短時間內(nèi)重復觸發(fā)同一個行為,導致重復請求后端數(shù)據(jù),上一個接口的數(shù)據(jù)還未全部渲染完成,后一個接口的數(shù)據(jù)已經(jīng)回來了,導致頁面渲染頻繁。

function.png
通過 setTimeout 實現(xiàn)
<div>
<h2>添加防抖后</h2>
<input type="text" id="debounce" />
</div>
function debounce(func, wait, options) {
let timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(() => {
func(...arguments); // 或 func.apply(null, arguments)
}, wait);
};
}
function handleDebounceInput(e) {
console.log("debounce val", e.target.value);
}
// 獲取頁面DOM元素
const debounce_input = document.getElementById("debounce");
debounce_input.oninput = debounce(handleDebounceInput, 800);
Lodash 的實現(xiàn)方式
函數(shù)節(jié)流 以第一次為準
指定時間間隔內(nèi)只執(zhí)行一次回調(diào)函數(shù),以第一次為準
例如:多次點擊登錄按鈕
通過時間戳實現(xiàn)
<div>
<h2>添加節(jié)流后</h2>
<input type="text" id="throttle" />
</div>
function throttle(func, wait) {
let start = Date.now();
return function () {
const now = Date.now();
if (now - start > wait) {
func(...arguments); // 或 func.apply(null, arguments)
start = Date.now();
}
};
}
function handleThrottleInput(e) {
console.log("throttle val", e.target.value);
}
// 獲取頁面DOM元素
const throttle_input = document.getElementById("throttle");
throttle_input.oninput = throttle(handleThrottleInput, 800);
通過 setTimeout 實現(xiàn)
//節(jié)流-通過setTimeout 實現(xiàn)
function throttle(func, wait) {
let timer = null;
return function () {
if (!timer) {
func(...arguments);
timer = setTimeout(() => {
timer = null;
}, wait);
}
};
}