其他分享
首页 > 其他分享> > 防抖与节流

防抖与节流

作者:互联网

<!DOCTYPE html>
<html lang="zh-CN">
<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>
</head>
<body>
  <input class="input1" type="text">
  <input class="input2" type="text">
  <script>
    // 1、防抖
    var ipt1 = document.querySelector('.input1')
    var timer1 = null
    ipt1.addEventListener('input',() => {
      // 事件触发首先要清除定时器
      clearTimeout(timer1)
      timer1 = setTimeout(()=>{
        console.log('防抖')
      },2000)
    })
    // 2、节流
    var timer2 = null
    var ipt2 = document.querySelector('.input2')
    ipt2.addEventListener('input',() => {
      if(timer2) return
      timer2 = setTimeout(()=>{
        console.log('节流')
        timer2 = null
      },2000)
    })
    
  </script>
</body>
</html>

标签:防抖,节流,timer2,timer1,var,null
来源: https://blog.csdn.net/weixin_49696014/article/details/121504703