其他分享
首页 > 其他分享> > 10、防抖和节流

10、防抖和节流

作者:互联网

1. 什么是防抖

【解释】: 防抖策略(debounce)是当事件被触发后,延迟 n 秒后再执行回调,如果在这 n 秒内事件又被触发,则重新计时。

【图解】:
在这里插入图片描述
【作用】:

【实现输入框的防抖】:

var timer = null                    // 1. 防抖动的 timer

 function debounceSearch(keywords) { // 2. 定义防抖的函数
    timer = setTimeout(function() {
    // 发起 JSONP 请求
    getSuggestList(keywords)
    }, 500)
 }

 $('#ipt').on('keyup', function() {  // 3. 在触发 keyup 事件时,立即清空 timer
    clearTimeout(timer)
    // ...省略其他代码
    debounceSearch(keywords)
 })

【实现建议框缓存】:

2、什么是节流

【解释】: 减少一段时间内事件的触发频率。也叫节流策略。

【图解】:
在这里插入图片描述
【应用】

【鼠标跟随案例】:

<!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>Document</title>
  <script src="./lib/jquery.js"></script>
  <style>
    html,
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
    }

    #angel {
      position: absolute;
    }
  </style>
</head>

<body>
  <img src="./angel.gif" alt="" id="angel" />

  <script>
    $(function () {
      // 获取图片元素
      var angel = $('#angel')
      // 绑定鼠标移动事件
      $(document).on('mousemove', function (e) {
        // 获取鼠标到x和y轴的距离设置给图片的高和左
        $(angel).css('top', e.pageY-40 + 'px').css('left', e.pageX-40 + 'px')
      })
    })
  </script>
</body>

</html>

3、节流阀

【解释】:

【使用节流优化】:

<!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>Document</title>
  <script src="./lib/jquery.js"></script>
  <style>
    html,
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
    }

    #angel {
      position: absolute;
    }
  </style>
</head>

<body>
  <img src="./angel.gif" alt="" id="angel" />

  <script>
    $(function () {
      // 定义一个节流阀
      var timer = null;
      // 获取图片元素
      var angel = $('#angel')
      // 绑定鼠标移动事件
      $(document).on('mousemove', function (e) {
        // 判断节流阀是否为空
        if (timer) return
        // 控制节流阀的时间
        timer = setTimeout(function () {
          // 获取鼠标到x和y轴的距离设置给图片的高和左
          $(angel).css('top', e.pageY - 40 + 'px').css('left', e.pageX - 40 + 'px')
          // 清空节流阀
          timer = null
        }, 100)
      })
    })
  </script>
</body>

</html>

标签:function,10,防抖,缓存,节流,angel,timer,节流阀,keywords
来源: https://blog.csdn.net/m0_54861649/article/details/123052405