小程序搜索事件,用户输入便触发搜索方法
timer:null,
bindSearchInput(e) {
this.setData({
quickSearch: e.detail.value
})
clearTimeout(this.timer)
this.timer=setTimeout(() => {
this.searchFun()
}, 1000)
},
防抖事件
防抖:n秒后再执行该事件,若在n秒内被重复触发,则重新计时。
function debounce(fun, wait) {
let timer
return (...args) => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fun(...args)
}, wait)
}
}
btn.addEventListener('click', debounce(btnHandle, 1000))
节流
节流:高频事件触发,每隔一段时间执行。
function throttle1(fun, wait) {
let time1 = 0
return (...args) => {
const time2 = Date.now()
const timeInterval = time2 - time1
if (timeInterval < wait) {
return
} else {
time1 = time2
fun(...args)
}
}
}
window.onresize = throttle1(() => {
console.log(24)
}, 1000)
// 页面在频繁resize的时候,控制台会每隔1秒打印一次
// 第二种方法,利用定时器实现
function throttle2(fun, wait) {
let timer
return (...args) => {
if (timer) {
return
} else {
timer = setTimeout(() => {
timer = null
fun(...args)
}, wait)
}
}
}