前端函数防抖、节流

函数进阶

函数防抖(debounce)以最后一次为准

解决办法:延迟 n 秒执行,只执行 n 毫秒内最后一次触发,提升执行速度,避免接口过载,节省资源

短时间内重复触发同一个行为,导致重复请求后端数据,上一个接口的数据还未全部渲染完成,后一个接口的数据已经回来了,导致页面渲染频繁。

function.png

通过 setTimeout 实现

添加防抖后

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 的实现方式


函数节流 以第一次为准

指定时间间隔内只执行一次回调函数,以第一次为准

例如:多次点击登录按钮

通过时间戳实现

添加节流后

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 实现

//节流-通过setTimeout 实现
function throttle(func, wait) {
  let timer = null;
  return function () {
    if (!timer) {
      func(...arguments);
      timer = setTimeout(() => {
        timer = null;
      }, wait);
    }
  };
}

Lodash 的实现方式


参考

lodash

你可能感兴趣的:(前端函数防抖、节流)