微信小程序防抖、节流
点击事件绑个定时器
tap (e) {
clearTimeout(this.TimeID);
this.TimeID = setTimeout(() => {
//4.准备发送请求获取数据
console.log(111)
}, 1000);
},
/**
* 节流
* @param fn 需要节流的函数
* @param t 时间
*/
export const throttle = (ft, t) => {
let flag = true
const interval = t
return function (this, ...args) {
if (flag) {
fn.apply(this, args)
flag = false
setTimeout(() => {
flag = true
}, interval)
}
}
}
/**
* 防抖
* @param fn 需要防抖的函数
* @param t 时间
*/
export const debounce = (fn, t = 300) => {
let timeId = null
const delay = t
return function (this, ...args) {
if (timeId) {
clearTimeout(timeId)
}
timeId = setTimeout(() => {
timeId = null
fn.apply(this, args)
}, delay)
}
}
// js 中使用
addNumber = debounce(function(this: any){
this.setData({
number: this.data.number + 10
})
}, 300)
reduce = throttle(function(this: any) {
this.setData({
number: this.data.number - 1
})
}, 1000)
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: