小程序防抖

本文介绍了在小程序中如何应用防抖技术,确保队列中最多维持10个事件,超过限制则丢弃最早进入的事件。默认防抖时间为1000毫秒。策略包括检查更新时间以及在无旧事件时将新事件加入队列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

let debounce = {
  map:[],
  isValidClick:function(key, wait=1000){
    let item = this.getItem(key);
    if(!item){
      if(this.map.length >10){
        this.map.shift()
      }
      this.map.push({key:key,tick:new Date().getTime()});
      return true;
    }else{
      let now = new Date().getTime();
      let result = now - item.tick > wait;
      item.tick = now;
      return result;
    }
  },
 
  getItem:function(key){
    for(let i=0;i<this.map.length;i++){
      let item = this.map[i]
      if(item.key === key){
        return item
      }
    }
    return null
  }
}

module.exports = debounce

使用

const debounce = require("../../utils/debounce")


Page({
onAdd: function (e) {
    let state = app.globalData.userInfo.state;
    let isGetUserInfo = ((state & 1) === 1); //判断是否提交过用户信息
    let isGetMobil = ((state & 2) === 2); //判断是否已绑定手机

    if (!isGetUserInfo || !isGetMobil) {
      if (!isGetUserInfo) {
        wx.navigateTo({
          url: '/pages/login/wxLogin/wxLogin?index=-1'
        })
        return;
      }
      if (!isGetMobil) {
        wx.navigateTo({
          url: '/pages/login/login?index=-1'
        })
        return;
      }
    }
  
    if (debounce.isValidClick('game_on_add')) {     ///////////////使用
      wx.showModal({
        title: '温馨提示',
        content: '确定加入游戏吗?',
        showCancel: true,
        confirmColor: "#000",
        success: (res) => {
          if (res.confirm) {
            this.onRequest()
          }
        }
      })
      
    }
  },

})

保持队列里面只有10个事件 超过了干掉最先进来的;默认防抖时间是1000ms;

已存在就判断更新时间  没有就加进队列

简单明了  一看就懂  不做解释

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值