<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
  <title>节流和防抖</title>
</head>

<body>
  <ul>
    <li>防抖(debounce):无论执行多少次都以最后一次为准(电脑自动休眠就是经典的防抖)</li>
    <li>节流(throttle):调用了多次只要第一次调用有效( 单位时间内多次触发函数,也只有一次生效 )</li>
  </ul>
  <button id="debounce">防抖</button>
  <button id="throttle">节流</button>
  <script>
    //JS部分
    function move(e) {
      //通过事件对象获取dom对象
      var that = $(e.target);
      console.log(that.attr("id"));

      console.log("Hello World!");
    }
    // 防抖
    function debounce(fn) {
      var debItem = null
      return function() {
        var arg = arguments[0] //获取事件
        if (debItem) {
          clearTimeout(debItem)
        }
        debItem = setTimeout(function() {
          fn(arg) //事件传入函数
        }, 1000);
      }
    }
    // 节流
    function throttle(fn) {
      var thrItem = null
      return function() {
        var arg = arguments[0] //获取事件
        if (thrItem) {
          return
        }
        thrItem = setTimeout(function() {
          fn(arg) //事件传入函数
          thrItem = null
        }, 1000);
      }
    }
    $(document).ready(function() {
      $("#debounce").on('click', debounce(move));
      $("#throttle").on('click', throttle(move));
    });
  </script>
</body>

</html>