繁花似锦觅安宁,淡云流水度此生。
缘深缘浅随它去,花开花落总归尘。

js实现防抖、节流!

场景:按钮的点击事件

防抖:给定一个时间,不管怎么点击按钮,每点一次,都会在最后一次点击等待这个时间过后执行

节流:给定一个时间,不管这个时间你怎么点击,点上天,这个时间内也只会执行一次

直接上代码,走起来~

 html

<body>
  <button id="btn">点击我进行测试</button>
</body>

 防抖函数

<script>
  document.getElementById('btn').onclick = debounce(function () {
    test('hello', 'world')
  }, 2000)
  
  function test(a, b) {
    console.log(a, b)
  }
 // 防抖函数
function debounce(fn, delay) { var timer = null delay = delay || 200 return function () { var args = arguments var that = this clearTimeout(timer) timer = setTimeout(function () { fn.apply(that, args) }, delay) } } </script>

节流函数:

<script>
  document.getElementById('btn').onclick = throttle(function () {
    test('hello', 'world')
  }, 3000)
  function test(a, b) {
    console.log(a, b)
  }
 // 节流函数
  function throttle(fn, delay) {
    var lastTime = Date.now()
    var timer
    delay = delay || 200
    return function () {
      var args = arguments
      var nowTime = Date.now()
      if (lastTime && nowTime - lastTime < delay) {
        clearTimeout(timer)
        timer = setTimeout(function() {
          lastTime = nowTime
          fn.apply(this, args)
        }, delay)
      } else {
        lastTime = nowTime
        fn.apply(this, args)
      }
    }
  }
</script>   

 

posted @ 2021-03-08 23:22  良人非良  阅读(488)  评论(0)    收藏  举报