微信小程序 性能优化 减少数据请求- 防抖

 场景

.wxml中设置一个button 添加 点击事件

这个个按钮点击发AJAX请求,当用户再点击的时候,一不小心点击了很多次,那么这个事件函数就需要执行很多次,从而导致发送多次请求,这就会影响服务器性能和导致前端页面的重绘,所以我们需要解决这个问题,js 函数防抖就可以解决。不管用户点击多少次,最终只发送一次请求。

click:function(){
    console.log(222)
    wx.request({
      url: 'http://106.75.79.117:3000/contents',
      success:(res)=>{
        console.log(res)
      }
    })
  },

 解决方法

  1. 声明一个计时器
  2. 再使用计时器前需要清除一下这个计时器

此时不论点击多少次  只发送一个请求

data: {
    time:null
  },
  click:function(){
    let that = this
    clearTimeout(that.time)
      that.time = setTimeout(function(){
      console.log(222)
      wx.request({
        url: 'http://106.75.79.117:3000/contents',
        success:(res)=>{
          console.log(res)
        }
      })
    },1000)
  },

猜你喜欢

转载自blog.csdn.net/weixin_41040445/article/details/114682547