高阶函数之节流与防抖

  • 节流和防抖在我们的日常代码中经常会遇到,下面我们来认识一下节流和防抖的应用场景以及它们的定义。
定义
  • 相同点:两者的前提都是频繁触发
  • 不同点:
  • 节流:是确保函数特定的时间内至多执行一次。
  • 防抖:是函数在特定的时间内不被再调用后执行。
应用场景
  • 节流:鼠标连续多次click事件,mousemove 事件,监听滚动事件,比如是否滑到底部自动加载更多等等…
  • 防抖:输入框搜索自动补全事件,频繁操作点赞和取消点赞等等
防抖
<!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>
</head>
<body>
    <input type="text" id="name">
    <script>
      let input = document.getElementById('name');
      function debonce(func, context, delay){
        return function(){
          let args = [].slice.call(arguments);
          //再次执行时清空定时器,确保只执行一次
          func.id && clearTimeout( func.id );
          func.id = setTimeout( function(){
            func.apply(context,args);
          },delay);
        }
      }
      let debonceAjax = debonce(ajax, null, 2000);
      input.addEventListener('keyup',function(e){
        debonceAjax(e.target.value);
      });
      function ajax(data,type){
        console.log('ajax request ' + data + ' success');
      }
    </script>
</body>
</html>

节流

<!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>
    <style>
      li {
        height: 50px;
        margin: 20px;
        background: #ccc;
      }
    </style>
</head>
<body>
    <ul id="container"></ul>
    <script>
      let container = document.getElementById('container');
      let lisHtml = '';
      for(let i=0; i<30; i++){
        lisHtml += `<li>我是第 ${i} 个数据</li>`
      }
      container.innerHTML = (lisHtml);
      let throttleAjax = throttle(ajax, 1000);
      document.addEventListener('scroll',function(){
        throttleAjax('newData');
      })
      
      function throttle(fn, delay) {
        let lastTime; 
        let timer; 
        delay || (delay = 300); // 默认间隔为300ms
        return function() {
          let context = this;
          let args = arguments;
          let nowTime = +new Date(); // 获取系统当前的时间
            if (lastTime && nowTime < lastTime+ delay) { // 当前距离上次执行的时间小于设置的时间间隔
                clearTimeout(timer); // 清除定时器
                timer = setTimeout(function() { // delay时间后,执行函数
                  lastTime= nowTime ;
                  fn.apply(context, args);
                }, delay);
              } else { // 当前距离上次执行的时间大于等于设置的时间,直接执行函数
                lastTime= nowTime ;
                fn.apply(context, args);
              }
          };
        }


      function ajax(data){
        console.log('这里是最新数据'+ data)
      }
    </script>
</body>
</html>

节流防抖优化函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值