微信小程序节流函数中的闭包问题,闭包不起作用?

新手上路,请多包涵

写了一个节流函数,然后引入index页面

//节流函数
function throttle(fn,delay){
  
  let timer = null;
  return function(...args){
    let _this = this
    console.log(timer)
    if(!timer){
      timer = setTimeout(()=>{
        fn.apply(_this,...args)
        timer = null
      },delay)
      console.log(!timer)
    }
  }
}

module.exports = {
  throttle
}

index界面获取数据,通过上拉触底函数获取更多数据

//获取color
  getColorList(){
    wx.showLoading({
      title: '数据加载中',
    }),
    wx.request({
      url: 'https://www.escook.cn/api/color',
      method:"GET",
      timeout: 0,
      success: (result) => {
        console.log(result)
        this.setData({
          colorList:[...this.data.colorList,...result.data.data]
        })
      },
      fail: (res) => {},
      complete: (res) => {
        wx.hideLoading({
          success: (res) => {},
        })
      },
    })
  },
onReachBottom() {
     let a = util.throttle(this.getColorList,5000)
     a()
   },

想要通过闭包节流实现多次下拉在delay时间段内只出发一次,但是失败了,应该是闭包不起作用,多次上拉触底输出是这个样子
image.png
可以发现每次都检测出timer是null,每次上拉都会执行一次函数,想问一下,为什么这个节流函数里面的闭包没起作用呢?
如果我写的有问题,我应该怎么实现这个节流功能呢?

阅读 1.8k
1 个回答

确保 throttle 只调用一次,而不是每次 onReachBottom 都要调用它一次:

onReachBottom: util.throttle(function(){
    // 如果有问题的话就是 throttle 的问题
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题