JavaScript-基础10-防抖&节流

JavaScript-基础10-防抖&节流


在这里插入图片描述

//防抖
function debounce(func, wait, immediate) {
        let timer = null;
        let result;
        console.log(immediate);
        let debounce = function () {
          //解决event问题
          let args = arguments;
          clearTimeout(timer);
          if (immediate) { //立即执行(immediate == true)
            let callNow = !timer;
            timer = setTimeout(() => {
              timer = null;
            }, wait);
            if(callNow) result = func.apply(this, args);
          } else {//不立即执行(immediate == undefined)
            
            timer = setTimeout(() => {
              //箭头函数改变this指向,此时的this指向上下文的函数对象
              result = func.apply(this, args);
            }, wait);
          }

          return result;
        }
        //取消防抖
        debounce.cancel = function(){
          clearTimeout(timer);
          timer = null;
        }
        return debounce;
      }

在这里插入图片描述

//节流
function throttle(func, wait, options) {
        let context, result;
        let args;
        let old = 0
        let timeout = null;
        let throttle = function () {
          context = this;
          args = arguments;
          if (!options) options = {};
          let now = new Date().valueOf();
          if (options.leading === false && !old) {
            old = now;
          }
          if (now - old > wait) {
            if (timeout) {
              clearTimeout(timeout);
              timeout = null;
            }
            old = now;
            result = func.apply(context, args);
          } else if (!timeout && options.trailing !== false) {
            timeout = setTimeout(() => {
              old = new Date().valueOf();
              timeout = null;
              result = func.apply(context, args);

            }, wait);
          }
          return result;
        };
        throttle.cancel = function () {
          clearTimeout(timeout);
          old = 0;
          timeout = context = args = null;
        };
        return throttle;

      }

例子(注销的为节流代码,未注销的为防抖代码)

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title><s>
    <style>
      #container {
        width: 100%;
        height: 100px;
        background-color: skyblue;
        font-size: 36px;
        text-align: center;
        line-height: 100px;
      }
    </style>
  </s>
</head>

<body>
  <div id="container"></div>
  <button id="btn">取消防抖</button>
  <script src="https://cdn.bootcdn.net/ajax/libs/underscore.js/1.10.2/underscore-min.js"></script>
  <script>
    window.onload = function () {
      let count = 0;

      //执行方法
      function requestData(event) {
        // console.log(event);
        // console.log(this);
        document.getElementById("container").innerText = count++;
      }
      //防抖
      function debounce(func, wait, immediate) {
        let args, timer, result;
        let debounce = function () {
          clearTimeout(timer);
          args = arguments;
          if (immediate) {
            let callNow = !timer;
            timer = setTimeout(() => {
              timer = null;
            }, wait);
            if (callNow) result = func.apply(this, args);
          } else {
            timer = setTimeout(() => {
              result = func.apply(this, args);
            }, wait);
          }
          return result;
        };
        debounce.cancel = () => {
          clearTimeout(timer);
          timer = null;
        }

        return debounce;
      }

      //节流
      // function throttle(func, wait, options) {
      //   let context, result;
      //   let args;
      //   let old = 0
      //   let timeout = null;
      //   let throttle = function () {
      //     context = this;
      //     args = arguments;
      //     if (!options) options = {};
      //     let now = new Date().valueOf();
      //     if (options.leading === false && !old) {
      //       old = now;
      //     }
      //     if (now - old > wait) {
      //       if (timeout) {
      //         clearTimeout(timeout);
      //         timeout = null;
      //       }
      //       old = now;
      //       result = func.apply(context, args);
      //     } else if (!timeout && options.trailing !== false) {
      //       timeout = setTimeout(() => {
      //         old = new Date().valueOf();
      //         timeout = null;
      //         result = func.apply(context, args);

      //       }, wait);
      //     }
      //     return result;
      //   };
      //   throttle.cancel = function () {
      //     clearTimeout(timeout);
      //     old = 0;
      //     timeout = context = args = null;
      //   };
      //   return throttle;

      // }










      //防抖
      let req = debounce(requestData, 1000);
      document.getElementById("container").onmousemove = req;
      document.getElementById("btn").onclick = () => {
        console.log('55555');
        req.cancel();
      }


      //节流
      // document.getElementById("container").onmousemove = throttle(requestData, 2000, {
      //   leading: true, trailing: false
      // });


    }
  </script>
</body>

</html>

内容仅供学习参考,若有错误欢迎大家指正----WUCASE

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值