你是否在日常開發中遇到一個問題,實現一個按鈕的防二次點擊操作,否則用戶頻繁點擊很有可能導致頁面卡頓。
防抖動和節流本質是不一樣的。防抖動是將多次執行變為最后一次執行,節流是將多次執行變成每隔一段時間執行
防抖
任務頻繁觸發的情況下,只有任務觸發的間隔超過指定間隔的時候,任務才會執行。
data(){
timer: null //創建一個標記用來存放定時器的返回值
}
// 封裝定時器清除函數
clearTimer() {
if(this.timer) clearTimeout(this.timer)
}
goToNext(){
this.clearTimer() //如果已經設定過定時器了就把前一個定時器清除
//然后創建一個新的 setTimeout
this.timer = setTimeout(() => {
this.qaIndex = this.qaIndex + 1
this.currentBtn = ''
this.progress()
}, 500)
}
結合上面的代碼,我們可以了解到,在觸發點擊事件后,如果用戶再次點擊了,我們會清空之前的定時器,重新生成一個定時器。意思就是:這件事兒需要等待,如果你反復催促,我就重新計時!
節流
用戶點擊提交按鈕,假設我們知道接口大致的返回時間的情況下,我們使用節流,這里只允許用戶點擊一次
data(){
ageNum: '',
phoneNum: '',
btnDisable: false
}
submitFace(){
if(!this.ageNum){
wepy.showToast({
title: '請填寫您的年齡',
icon: 'none',
duration: 2000
})
}
if(!this.phoneNum){
wepy.showToast({
title: '請填寫微信/手機號',
icon: 'none',
duration: 2000
})
}
if(this.ageNum && this.phoneNum){
if(this.btnDisable) return // 2. 在函數開頭判斷標志是否為 true,為true 則中斷函數
wepy.showLoading({
title: '提交中...',
mask: true
})
this.btnDisable = true // 1. 防止多次提交不斷發請求
this.$emit('btnDisable',this.btnDisable)
wepy.request({
url: '/mobile/mina/face/save',
method: 'POST',
data: {
age: this.ageNum,
phone: this.phoneNum,
problemTypeList: this.saveTagList
}
}).then((res) => {
wepy.hideLoading()
if (res.resCode != 0) return
wepy.showToast({
title: '信息提交成功',
icon: 'success',
duration: 2000
})
this.btnDisable = false // 3. 交成功后重置為false 變為可點狀態
}
}
}