小程序开发搜索事件防抖

小程序搜索事件,用户输入便触发搜索方法

 timer:null,
  bindSearchInput(e) {
    
    this.setData({
      quickSearch: e.detail.value
    })
    clearTimeout(this.timer)
    this.timer=setTimeout(() => {
      
      this.searchFun()
    }, 1000)
    
    
  },
防抖事件

防抖:n秒后再执行该事件,若在n秒内被重复触发,则重新计时。

function debounce(fun, wait) {
      let timer
      return (...args) => {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fun(...args)
        }, wait)
      }
    }
btn.addEventListener('click', debounce(btnHandle, 1000))
节流

节流:高频事件触发,每隔一段时间执行。

 function throttle1(fun, wait) {
      let time1 = 0
      return (...args) => {
        const time2 = Date.now()
        const timeInterval = time2 - time1
        if (timeInterval < wait) {
          return
        } else {
          time1 = time2
          fun(...args)
        }
      }
    }
     window.onresize = throttle1(() => {
      console.log(24)
     }, 1000)
    // 页面在频繁resize的时候,控制台会每隔1秒打印一次
    // 第二种方法,利用定时器实现
    function throttle2(fun, wait) {
      let timer
      return (...args) => {
        if (timer) {
          return
        } else {
          timer = setTimeout(() => {
            timer = null
            fun(...args)
          }, wait)
        }
      }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值