函数的节流与防抖


一、函数的防抖

现在有一个场景, 用户在输入框里面输入数据, 用户每输入一次数据, 方法都会往服务器请求一次. 这样对服务器的压力会非常大

模拟场景

鼠标移动, 修改数值

<!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>Document</title>
  <style>
    .box {
      width: 100%;
      height: 300px;
      background-color: black;
      color: #fff;
      line-height: 300px;
      text-align: center;
      font-size: 20px;
    }
  </style>
</head>
<body>
  <div class="box">
  </div>

  <script>
    let count = 0
    let box = document.querySelector(".box")
    function doSomeThing() {
      box.innerHTML = count++
    }
    box.onmousemove = doSomeThing
  </script>
</body>
</html>

使用underscore库的debounce方法

_.debounce(要执行的函数, 多少秒后执行)

<script>
  let count = 0
  let box = document.querySelector(".box")
  function doSomeThing() {
    box.innerHTML = count++
  }
  box.onmousemove = _.debounce(doSomeThing, 1000)
</script>

二、手动封装函数的防抖

// 防抖函数, 第一个参数: 要执行的函数, 第二个参数: 等待的时间
function debounce(func, wait) {
  let timeout;
  return function() {
    let context = this
    // mouseEvent
    let args = arguments
    clearTimeout(timeout);
    timeout = setTimeout(function(){
      // 修改tis的指向
      func.apply(context, args)
    }, wait)
  }
}

三、封装函数的节流

触发事件, 每隔一段时间, 只执行一次事件

<!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>Document</title>
  <style>
    .box {
      width: 100%;
      height: 300px;
      background-color: black;
      color: #fff;
      line-height: 300px;
      text-align: center;
      font-size: 20px;
    }
  </style>
</head>
<body>
  <div class="box"></div>

  <script>
    function throttle(func, wait){
      let context, args, timeout
      return function() {
        context = this
        args = arguments
        if(!timeout) {
          timeout = setTimeout(()=>{
            timeout = null
            func.apply(context, args)
          }, wait) 
        }
      }
    }


    let count = 0
    let box = document.querySelector(".box")
    function doSomeThing(e) {
      console.log(e);
      box.innerHTML = count++
    }
    box.onmousemove = throttle(doSomeThing, 1000)
  </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值