防抖和截流的代码

名词解释

  1. 防抖 顾名思义,防止抖动,抬腿一秒钟你抖了100次,那指定是有脑血栓,你要是抬腿后一秒后才抖一次,那才是我们想要的。在一定时间内重复执行某动作,只执行最后一次
  2. 截流 顾名思义,截断流水的正常状态。有个元素周期表51,一直对你说话,重复的说,搞得你烦死了。这时候,你戴个耳塞,1秒后才听他说的内容,然后又戴上耳塞。这样你听的唠叨的话,就是1秒钟才能听到一次。在一定时间内容重复执行的动作,降低它的执行频次

代码

<!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>
    .div1 {
      background-color: red;
      margin-top: 10px;
      margin-bottom: 10px;
    }

    .div12 {
      background-color: yellow;
      margin-top: 30px;
    }

    .div2 {
      background-color: blue;
      margin-top: 20px;
    }
  </style>
</head>

<body>
  <input class="input-throttle" type="text">
  <div class="input-copy_container">
    <div>input的输入值</div>
    <div class="input-copy_text"></div>
  </div>
  <div class="text-cursor"></div>
</body>
<script>
  $body=document.querySelector('body')
  $textCursor=document.querySelector('.text-cursor')
  $inputThrottle=document.querySelector('.input-throttle')
  $inputCopyText=document.querySelector('.input-copy_text')

  // 鼠标的回调
  function mousemoveCallback(e) {
    console.log('clientX,clientY', 'x'+e.clientX+'  y'+e.clientY);
    $textCursor.innerText='x'+e.clientX+'  y'+e.clientY
  }

  // 输入框的回调
  function inputCallback(e) {
    console.log('e :>> ', e.srcElement.value);
    $inputCopyText.textContent=e.srcElement.value
  }

  // 防抖 wait 毫秒,在wait内容执行第二,就取消之前的定时任务
  function debounce(func, wait) {
    let timeId=null;
    return (...args) => {
      if (timeId) {
        clearTimeout(timeId)
      }
      timeId=setTimeout(() => {
        func.apply(this, args)
      }, wait);
    }
  }

  // 截流
  function throttle(func, wait) {
    // 定义一个时间戳,当再次执行该函数时的时间戳,如果小于wait则,清空如果大于则不管
    let timeId=null;
    let prevTime=new Date().getTime();
    let nowTime;
    return (...args) => {
      const nowTime=new Date().getTime()
      if (nowTime-prevTime>wait) {
        prevTime=nowTime
        func.apply(this, args)
      }
    }
  }

  $inputThrottle.addEventListener('input', throttle(inputCallback, 2*1000)) // 输入框测试防抖
    document.addEventListener('mousemove', throttle(mousemoveCallback, 2*1000))   // 鼠标操作测试截流
</script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值