小程序防止重复点击或重复触发事件
发布于 3 年前 作者 qiang90 3685 次浏览 来自 分享

可设置全局变量和全局函数,直接使用app唯一实例调用,方便快捷。

在app.js下

App({
  globalData: {
    PageActive: true
  },
  preventActive (fn) {
    const self = this
    if (this.globalData.PageActive) {
      this.globalData.PageActive = false
      if (fn) fn()
      setTimeout(() => {
        self.globalData.PageActive = true
      }, 1500); //设置该时间内重复触发只执行第一次,单位ms,按实际设置
    } else {
      console.log('重复点击或触发')
    }
  }
})

其他page下调用

index.wxml

<button bindtap="tap">点击</button>

index.js

Page({
  tap (e) {
    getApp().preventActive(()=>{
      //code...
    })
  }
})
2 回复
/**
 * 节流
 * [@param](/user/param) fn 需要节流的函数
 * [@param](/user/param) t 时间
 */
export const throttle = (ft, t) => {
  let flag = true
  const interval = t
  return function (this, ...args{
    if (flag) {
      fn.apply(this, args)
      flag = false
      setTimeout(() => {
        flag = true
      }, interval)
    }
  }
}

/**
 * 防抖
 * [@param](/user/param) fn 需要防抖的函数
 * [@param](/user/param) t 时间
 */
export const debounce = (fn, t = 300) => {
  let timeId = null
  const delay = t
  return function (this, ...args{
    if (timeId) {
      clearTimeout(timeId)
    }
    timeId = setTimeout(() => {
      timeId = null
      fn.apply(this, args)
    }, delay)
  }
}
// js 中使用
addNumber = debounce(function(thisany){
  this.setData({
   numberthis.data.number + 10
  })
}, 300)
reduce = throttle(function(thisany{
  this.setData({
   numberthis.data.number - 1
  })
}, 1000)

思路不错,代码量确实精简。赞了👍

回到顶部