一、什麼是前端防抖?
前端防抖指的是在某個時間段內,如果有多個相同事件同時被觸發,只會執行最後一次觸發事件的函數,並且可以設置等待時間,如果在等待時間內有新的事件觸發,就需要重新等待,等待時間結束後才會執行函數。常用於解決重複事件觸發導致的瀏覽器性能問題。
二、前端防抖的應用場景
1、輸入框搜索實時聯想功能:每當用戶輸入一個字元就會發起請求,如果頁面中有多個輸入框,會導致頻繁的請求,使用前端防抖可以減少請求次數。
function debounce(func, delay) {
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
function search() {
// 實現搜索功能
}
const inputElement = document.querySelector('input');
inputElement.addEventListener('input', debounce(search, 300));
2、頁面滾動懶載入:用戶可能不會看到頁面所有內容,當頁面滾動到某個位置時才會載入一部分內容,如果每滾動一個像素就會發起一次請求,會嚴重影響頁面性能,使用前端防抖可以減少請求次數。
function debounce(func, delay) {
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
function loadContent() {
// 載入內容
}
window.addEventListener('scroll', debounce(loadContent, 300));
三、前端防抖的實現方式
前端防抖有兩種實現方式,一種是使用setTimeout函數,一種是使用requestAnimationFrame函數,兩種方式都可以有效地避免不必要的請求。
1、使用setTimeout函數實現
function debounce(func, delay) {
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
上面的代碼中,timer表示定時器的編號,當事件觸發時,會先判斷是否有已經存在的定時器,如果有,則清除已有定時器,然後重新設置一個新的定時器,等待一段時間後執行函數。
2、使用requestAnimationFrame函數實現
requestAnimationFrame函數可以在瀏覽器繪製下一幀之前執行任務,可以減少不必要的重繪,從而提高性能。
function debounce(func, delay) {
let timer;
return function(...args) {
if (timer) {
cancelAnimationFrame(timer);
}
timer = requestAnimationFrame(() => {
func.apply(this, args);
}, delay);
};
}
與使用setTimeout函數實現的代碼類似,只是將setTimeout函數替換成了requestAnimationFrame函數。
四、前端防抖的優化方式
前端防抖雖然可以解決頻繁觸發事件的問題,但是如果事件觸發過於頻繁,也會導致大量的請求堆積,影響用戶體驗。為了避免這種情況,可以對前端防抖進行優化。
1、立即執行一次:如果用戶需要立即執行函數,可以在函數執行前加上一個立即執行的代碼塊。
function debounce(func, delay, immediate) {
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer);
}
if (immediate) {
immediate = false;
func.apply(this, args);
}
timer = setTimeout(() => {
if (!immediate) {
func.apply(this, args);
}
}, delay);
};
}
2、取消防抖:如果用戶不需要某個事件的防抖功能,可以取消防抖。
function debounce(func, delay) {
let timer;
const debounceFunc = function(...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
debounceFunc.cancel = function() {
clearTimeout(timer);
};
return debounceFunc;
}
const inputElement = document.querySelector('input');
const debounceSearch = debounce(function() {
// 實現搜索功能
}, 300);
inputElement.addEventListener('input', debounceSearch);
// 取消防抖
debounceSearch.cancel();
五、總結
前端防抖是一種常用的優化技術,可以避免不必要的請求,提高網頁的性能和用戶體驗。通過本文的介紹,我們了解了前端防抖的實現方式和優化方式,可以更好地應用於實際開發中。
原創文章,作者:YESBU,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/332735.html
微信掃一掃
支付寶掃一掃