前端函數(shù)防抖、節(jié)流

函數(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);
    }
  };
}

Lodash 的實現(xiàn)方式


參考

lodash

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容