性能优化之节流和防抖

一、节流

函数节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

函数实现:

// func是用户传入需要防抖的函数
// wait是等待时间
const throttle = (func,wait) => {
  // 上一次执行该函数的时间
  let lastTime = 0
  return function(...args) {
    // 当前时间
    let now = +new Date()
    // 将当前时间和上一次执行函数时间对比
    // 如果差值大于设置的等待时间就执行函数
    if (now - lastTime > wait) {
      lastTime = now
      func.apply(this, args)
    }
  }
}

setInterval(
  throttle(() => {
    console.log(1)
  }, 500),
  1
)

使用场景:

  • 游戏中的刷新率
  • DOM元素拖拽
  • Canvas画笔功能

二、防抖

函数防抖(debounce):当持续触发事件时,一定时间段内没有再次触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

函数实现:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>debounce</title>
  </head>
  <body>
    <button id="btn" style="height: 50px;width: 100px;">
      连续点击呀,我防抖啦
    </button>
  </body>
  <script>
    function debounce(fn, wait) {
      var timer = null;
      return function() {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(function() {
          fn.apply(this, arguments);
        }, wait);
      };
    }

    var fn = function() {
      console.log(1);
    };
    let btn = document.getElementById("btn");
    btn.addEventListener("click", debounce(fn, 1000), false);
  </script>
</html>

使用场景:

  • 给按钮加函数防抖,防止表单多次提交
  • 对于输入框连续输入进行AJAX验证时,用函数防抖能有效减少请求次数
  • 判断scroll是否滑到底部,滚动事件+函数防抖

三、区别

节流是在指定时间内只执行一次,防抖是在指定时间内没有再次触发时执行,如果一直触发知道最后一次完成后不在触发了才执行。

发布了67 篇原创文章 · 获赞 4 · 访问量 5974

猜你喜欢

转载自blog.csdn.net/DZY_12/article/details/103109573