【自学】4.22 防抖/节流

每天写点玩玩

4.22

  • 简易debounce/throttle
    function debounce (fn, delay) {
      let timer = null
      return function () {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn.apply(this, arguments)
        }, delay)
      }
    }

    function throttle (fn, interval) {
      let lasttime = new Date().getTime()
      return function () {
        let nowtime = new Date().getTime()
        if (nowtime - lasttime >= interval) {
          fn.apply(this, arguments)
          lasttime = nowtime
        }
      }
    }
    const input = document.querySelector('input')
    let totalcount = 0
    function change (event) {
      console.log(`第${++totalcount}次请求`, event)
    }
    //input.oninput = debounce(change, 1000)
    input.oninput = throttle(change, 2000)
  • 带有取消功能的debounce
    function debounce (fn, delay, immediate = false) {
      let timer = null
      const _debounce = function () {
        if (timer) {
          clearTimeout(timer)
        }
        if (immediate) { //立即执行一次
          fn.apply(this, arguments)
          immediate = false
        } else {
          timer = setTimeout(() => {
            fn.apply(this, arguments)
            isinvoke = true
          }, delay)
        }
      }
      _debounce.cancel = function () {
        if (timer) {
          clearTimeout(timer) //清除计时器
        }
      }
      return _debounce
    }
    
    const input = document.querySelector('input')
    let totalcount = 0
    function change (event) {
      console.log(`第${++totalcount}次请求`, event)
    }
    input.oninput = debounce(change, 1000, immediate = true)
    const cancelbutton = document.querySelector('button')
    cancelbutton.onclick = function () {
      input.oninput.cancel()
    }
  • 防抖使用场景举例
    1 用户在输入框内连续输入一串字符的时候,可以规定在用户输入完之后再执行查询
    2 频繁点击按钮,触发某个事件
    3 用户缩放浏览器的resize事件
    4 监听页面滚动事件

  • 节流使用场景举例
    1 频繁点击按钮,触发某个事件
    2 监听页面滚动事件
    3 监听鼠标移动事件
    4 游戏中的一些设计等


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值