关于微信小程序中使用函数节流心得

661 阅读1分钟
  1. 首先要在utils文件里面把这个函数封装,marginTime是等待时间。比如第一次点击了这个事件后想让它在多久内不会再次触发,并且暴露出去。
const throttleFunc = function throttleFunc(func, marginTime) {
  if (marginTime == undefined || marginTime == null) {
    marginTime = 2000
  }
  let lastTime = null
  return function () {
    let currentTime = + new Date()
    if (currentTime - lastTime > marginTime || !lastTime) {
      func.apply(this, arguments)
      lastTime = currentTime
    }
  }
}

module.exports = {
  throttleFunc
}
  1. 在需要使用这个封装的节流函数的页面引入
var throttleFunc = require('../../utils/util')


// weixinLogin为你的点击事件,第一个throttleFunc为↑var定义的变量方法,第二个throttleFunc为在utils文件里面const定义的常量方法
weixinLogin:throttleFunc.throttleFunc(function () {
    // 此处为你想写的点击事件
},null),
// 此处的null为utils文件中函数接收的第二个参数,如果不填/填null,则默认的marginTime为2s,也可以填自己想设定的时间。

3.小程序中函数的节流到此使用完毕。