js防抖debounce和节流throttle区别和实现

js防抖和节流区别和实现

防抖【debounce】

当持续触发事件的时候,函数是完全不执行的,等最后一次触发结束的一段时间之后,再去执行。

使用场景【输入实时查询多次点击按钮

  • 持续触发不执行
  • 不触发的一段时间之后再执行

节流【throttle】

节流的意思是让函数有节制地执行,而不是毫无节制的触发一次就执行一次。什么叫有节制呢?就是在一段时间内,只执行一次。

使用场景【监听鼠标滚动下拉加载数据

  • 持续触发并不会执行多次
  • 到一定时间再去执行

防抖演示:

(频繁调用,只执行最后一次)
在这里插入图片描述

节流演示:

(频繁调用,每隔一段时间执行一次)
在这里插入图片描述

代码演示

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>防抖节流</title>
  <style>
    html,
    body{
      height: 100%;
    }
    #throttle,#debounce {
      height: 200px;
      width: 600px;
      border: 1px solid #eeeeee;
    }
  </style>
</head>

<body>
  <div id="throttle"></div>
  <div id="debounce"></div>

  <script>
    // ====== 节流
    const throttleBox = document.getElementById('throttle')
    function throttle(func, delay) {
      let run = true
      return function () {
        if (!run) {
          return  // 如果开关关闭了,那就直接不执行下边的代码
        }
        run = false // 持续触发的话,run一直是false,就会停在上边的判断那里,定时器里面函数执行完毕,会重置状态
        setTimeout(() => {
          func.apply(this, arguments)
          run = true // 定时器到时间之后,会把开关打开,我们的函数就会被执行
        }, delay)
      }
    }
    // 用法
    throttleBox.onmousemove = throttle(function (e) {
      throttleBox.innerHTML = `节流==${e.clientX}, ${e.clientY}`
    }, 1000)

    // ====== 防抖 ======
    const debounceBox = document.getElementById('debounce')
    function debounce(func, delay) {
      let timeout
      return function () {
        clearTimeout(timeout) // 如果持续触发,那么就清除定时器,定时器的回调就不会执行。
        timeout = setTimeout(() => {
          func.apply(this, arguments)
        }, delay)
      }
    }
    // 用法
    debounceBox.onmousemove = debounce(function (e) {
      debounceBox.innerHTML = `防抖==${e.clientX}, ${e.clientY}`
    }, 1000)

  </script>
</body>

</html>

封装防抖方法

export function debounce(func, wait = 1000, immediate = true) {
  let timeout
  let result
  return function(...args) {
    const context = this
    if (timeout) window.clearTimeout(timeout)
    if (immediate) {
      const callNow = !timeout
      timeout = setTimeout(() => {
        timeout = false
      }, wait)
      if (callNow) result = func.apply(context, args)
    } else {
      timeout = setTimeout(() => {
        func.apply(context, args)
      }, wait)
    }
    return result
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值