场景
.wxml中设置一个button 添加 点击事件
这个个按钮点击发AJAX请求,当用户再点击的时候,一不小心点击了很多次,那么这个事件函数就需要执行很多次,从而导致发送多次请求,这就会影响服务器性能和导致前端页面的重绘,所以我们需要解决这个问题,js 函数防抖就可以解决。不管用户点击多少次,最终只发送一次请求。
click:function(){
console.log(222)
wx.request({
url: 'http://106.75.79.117:3000/contents',
success:(res)=>{
console.log(res)
}
})
},
解决方法
- 声明一个计时器
- 再使用计时器前需要清除一下这个计时器
此时不论点击多少次 只发送一个请求
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)
},