2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Function anti-shake is actually a necessary skill for front-end students. I have been lazy and used page loading or button loading to achieve it. Recently, when developing WeChat applets, too much loading will bring a bad experience. At the same time, it is not easy to use loading to prevent shaking when jumping pages. Therefore, there will be a situation where a page will be cut multiple times if you click it multiple times in a row, so you have to use the anti-shake function to achieve it.
Without further ado, let's get straight to the code
/* 防抖函数封装 */
let timer
export const debounce = (fn, delay = 500) => {
return (...args) => { // 传入形参!!!
let that = this
timer && clearTimeout(timer)
timer = setTimeout(function () {
console.log("防抖函数执行", args)
fn.apply(that, args) // 用apply指向调用debounce的对象,相当于this.fn(args);
}, delay)
}
}
I have also seen many wrapper functions written by other students. Either they do not accept formal parameters, resulting in the external parameters being unable to be obtained in the anti-shake function, or they throw the timer definition into the function, resulting in the timer being redefined for each click, but the purpose of clearing the timer is not achieved.
export function goPage(url) {
debounce((url) => {
url && wx.navigateTo({ url })
})(url)
}
// 页面调用
goPage('.pages/home/index')
gotoShop(value) {
debounce((value) => {
// 接收外部传来的value参数,进行后续逻辑处理
})(value) // 接收外围函数的参数,丢到防抖函数里,有兴趣的同学也可以了解一下闭包
},
At present, the above two types are more widely used. If you like them, please like them.