防抖函数第二遍

<!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" />
    <title>防抖函数第二遍</title>
  </head>
  <body>
    <div id="main" style="width: 100%; height: 300px; border: 1px solid red"></div>
    <button id="btn">点击阻止</button>
    <script>
      const main = document.getElementById('main');
      const btn = document.getElementById('btn');
      let count = 0;
      function doSomething(e) {
        console.log(e);
        console.log(this);
        count++;
        main.innerText = count;
      }
      main.onmousemove = debounce(doSomething, 1000, true);
      function debounce(func, delay, immediate) {
        let timer, result;
        let debounced = function () {
          let context = this;
          let args = arguments;
          clearTimeout(timer);
          if (immediate) {
            let callNow = !timer;
            timer = setTimeout(function () {
              timer = null;
            }, delay);
            if (callNow) result = func.apply(context, args);
          } else {
            timer = setTimeout(function () {
              func.apply(context, args);
            }, delay);
          }
          return result;
        };
        return debounced;
      }
      let concept = `事件处理函数需要延迟一段时间后执行,如果在这段时间,该函数再次被调用,则重新计算延迟时间,若延迟时间内没有再次调用,则执行函数相应逻辑`;
      let environment = `scroll滚动事件;搜索框输入查询;表单验证;按钮提交;监听窗口变化 onresize 事件`;
    </script>
  </body>
</html>

 

posted @ 2022-05-08 11:19  苹果π  阅读(9)  评论(0编辑  收藏  举报