JavaScript防抖與節(jié)流怎樣減少請(qǐng)求次數(shù)

小樊
81
2024-10-25 22:14:28

在 JavaScript 中,防抖(debounce)和節(jié)流(throttle)是兩種常用的優(yōu)化高頻率觸發(fā)事件的技術(shù),它們都可以用來(lái)減少請(qǐng)求次數(shù)。

  1. 防抖(debounce): 防抖的基本原理是在一定時(shí)間內(nèi),無(wú)論觸發(fā)多少次事件,都只執(zhí)行一次指定的函數(shù)。當(dāng)事件停止觸發(fā)后,才會(huì)再次執(zhí)行。適用于如輸入框?qū)崟r(shí)搜索、窗口大小調(diào)整等場(chǎng)景。

實(shí)現(xiàn)方法:

function debounce(func, wait) {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}

使用示例:

const searchInput = document.querySelector('#search-input');
const fetchData = () => { /* 請(qǐng)求數(shù)據(jù)的操作 */ };

const debouncedFetchData = debounce(fetchData, 500);
searchInput.addEventListener('input', debouncedFetchData);
  1. 節(jié)流(throttle): 節(jié)流的基本原理是在一定時(shí)間內(nèi),只執(zhí)行一次指定的函數(shù)。與防抖不同的是,節(jié)流不會(huì)因?yàn)槭录倪B續(xù)觸發(fā)而立即執(zhí)行,而是在固定的時(shí)間間隔后執(zhí)行。適用于如滾動(dòng)加載、鼠標(biāo)移動(dòng)等場(chǎng)景。

實(shí)現(xiàn)方法:

function throttle(func, wait) {
  let lastTime = 0;
  return function () {
    const context = this;
    const args = arguments;
    const nowTime = Date.now();
    if (nowTime - lastTime > wait) {
      func.apply(context, args);
      lastTime = nowTime;
    }
  };
}

使用示例:

const scrollContainer = document.querySelector('#scroll-container');
const loadData = () => { /* 請(qǐng)求數(shù)據(jù)的操作 */ };

const throttledLoadData = throttle(loadData, 200);
scrollContainer.addEventListener('scroll', throttledLoadData);

通過(guò)這兩種技術(shù),我們可以有效地減少高頻率觸發(fā)事件的請(qǐng)求次數(shù),提高程序的性能。

0