函数防抖和函数节流

是函数防抖就是:

在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时
我们最经常用的就是输入框 搜索、添加等

举个搜索框的例子

<body>

  <input type="text" id="text">
</body>
 <script>
  function _debounce(fn,delay){
    var delay = delay || 400
    var timer
    return function(){
      var th = this
      var args = arguments
      if(timer){
        clearTimeout(timer)
      }
      timer = setTimeout(function(){
        timer = null
        fn.apply(th,args)
      }, delay);
    }
  }

  var txt = document.querySelector('#text').value

  txt.addEventListener('input',_debounce(
    function(){
      console.log(我不是不间断的打印) 
    }
    ))

</script>

此时的打印的内容 就不是 你输入一个 打印一个 而是隔了400毫秒 才打印你输入的内容

函数节流:

规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效

function _throttle(fn,delay){
    var last;
    var timer
    var delay = delay || 200
    return function(){
      var now = +new Date()
      var that = this
      var arg=arguments
      if(last && now-last<delay){
        clearTimeout(timer)
        timer = setTimeout(function(){
          timer = null
          last = now
          fn.apply(that,arguments)
        }, delay);
      }else{
        last = now
        fn.apply(that,arg)
      }
    }
  }

应用场景

_debounce
search搜索联想,用户在不断输入值时,用防抖来节约请求资源。

throttle

鼠标不断点击触发,mousedown(单位时间内只触发一次)
拖拽事件,每拖动1px都会触发onmousemove(可以用throttle优化,每秒触发一次)

盒子跟随鼠标移动

<style>
    #box {
      width: 100px;
      height: 100px;
      background-color: skyblue;
      position: absolute;  //必须要有定位 否则 是实现不了的
    }
  </style>
</head>

<body>
  <div id="box"></div>


</body>
<script>
  var max = document.getElementById('box')
  var doc = document.documentElement
   doc.onmousemove = function (e) {
    console.log(e);
     max.style.left = e.x - 50 + 'px'
     max.style.top = e.y - 50 + 'px'
  }
  </script>
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值