防抖函数三个参数第一遍

<!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 = 1;
      function doSomething(e) {
        console.log(e);
        console.log(this);
        count++;
        console.log(count);
      }
      main.onmousemove = debounce(doSomething, 1000, true);
      function debounce(func, delay, immediate) {
        let timer;
        let debounced = function () {
          let context = this;
          let args = arguments;
          clearTimeout(timer);
          if (immediate) {
            let callNow = !timer;
            timer = setTimeout(function () {
              timer = null;
            }, delay);
            if (callNow) func.apply(context, args);
          } else {
            timer = setTimeout(function () {
              func.apply(context, args);
            }, delay);
          }
        };
        debounced.cancel = function () {
          clearTimeout(timer);
          timer = null;
        };
        return debounced;
      }
    </script>
  </body>
</html>

 

posted @ 2022-05-09 14:46  苹果π  阅读(115)  评论(0编辑  收藏  举报