廢話不多說,開箱即用
# HTML
<h2>防抖與節流</h2>
<input class="antiShake" placeholder="請輸入-防抖">
<div class="throttle">節流</div>
# 防抖
/**
* @func 防抖:用戶短時間內多次觸發請求,只發起最后一次,將多個請求變成一次
* @desc 核心:一定時間內沒有繼續操作后執行處理函數。時間范圍內只要來新請求,立刻取消上一次操作。新請求比老請求更有業務價值
* @desc 經典案例:模糊搜索
*/
let telInput = document.querySelector('.antiShake')
// 未防抖情形
// telInput.addEventListener('input', (e) => {
// request()
// })
// 加了防抖 - antiShake通過閉包返回了函數
telInput.addEventListener('input', antiShake(request, 2000))
// 防抖函數 (本案例利用閉包實現,這樣無需再antiShake外部定義timeout變量)
function antiShake(fn, wait) {
let timeout = null
return args => {
if (timeout) clearTimeout(timeout)
timeout = setTimeout(fn, wait)
}
}
function request() {
console.log('發起請求了')
}
# 節流
/**
* @func 節流:用戶的某些操作導致重復的發起相同的請求,只發起第一次
* @desc 應用場景:提交表單,點擊提交按鈕,告片的監聽事件如touchmove
*/
let box = document.querySelector('.throttle')
// 未節流情形
// box.addEventListener('touchmove', (e) => {
// request()
// })
// 加了節流:
box.addEventListener('touchmove', throttle(request, 2000))
// 節流函數:觸發后開始計時,時間間隔內再過來的請求直接忽略,計時完成執行函數后,再接收下一個請求
function throttle(event, wait) {
let timer = null
return args => {
if (!timer) {
timer = setTimeout(() => {
event()
timer = null
}, wait)
}
}
}
function request() {
console.log('發起請求了')
}