美文网首页
前端函数防抖、节流

前端函数防抖、节流

作者: 殷川 | 来源:发表于2021-11-29 10:26 被阅读0次

函数进阶

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

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

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

function.png

通过 setTimeout 实现

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


函数节流 以第一次为准

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

例如:多次点击登录按钮

通过时间戳实现

<div>
  <h2>添加节流后</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 实现

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

Lodash 的实现方式


参考

lodash

相关文章

网友评论

      本文标题:前端函数防抖、节流

      本文链接:https://www.haomeiwen.com/subject/mwgkxrtx.html