美文网首页
微信小程序防止多次点击,函数延迟执行

微信小程序防止多次点击,函数延迟执行

作者: 大海请带我走 | 来源:发表于2023-02-20 17:39 被阅读0次
//util.js
// 延迟执行函数
// fn 需要延迟执行的函数
// gapTime  需要延迟的时间
function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
      gapTime = 1000
  }
  let _lastTime = null
  // 返回新的函数
  return function () {
      let _nowTime = + new Date()
      if (_nowTime - _lastTime > gapTime || !_lastTime) {
          fn.apply(this, arguments)   //将this和参数传给原函数,不然e是'undefine'
          _lastTime = _nowTime
      }
  }
}
module.exports = {
  throttle,
}

例子:

var utils = require('../../../utils/util');

btnClickAction: utils.throttle(function(e) {
    var sts = e.currentTarget.dataset.sts;
    console.log('订单id = ',sts);
    this.setData({
      sts: sts
    });
    console.log(e)
    console.log((new Date()).getSeconds())
  },600),   //延迟600ms

参考:https://mp.weixin.qq.com/s/3FZJ0nQLhj9PCi0pfBjc9A

相关文章

网友评论

      本文标题:微信小程序防止多次点击,函数延迟执行

      本文链接:https://www.haomeiwen.com/subject/krygkdtx.html