在 JavaScript 中,防抖(debounce)和節(jié)流(throttle)是兩種常用的優(yōu)化高頻率觸發(fā)事件的技術(shù),它們都可以用來(lái)減少請(qǐng)求次數(shù)。
實(shí)現(xiàn)方法:
function debounce(func, wait) {
let timeout;
return function () {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}
使用示例:
const searchInput = document.querySelector('#search-input');
const fetchData = () => { /* 請(qǐng)求數(shù)據(jù)的操作 */ };
const debouncedFetchData = debounce(fetchData, 500);
searchInput.addEventListener('input', debouncedFetchData);
實(shí)現(xiàn)方法:
function throttle(func, wait) {
let lastTime = 0;
return function () {
const context = this;
const args = arguments;
const nowTime = Date.now();
if (nowTime - lastTime > wait) {
func.apply(context, args);
lastTime = nowTime;
}
};
}
使用示例:
const scrollContainer = document.querySelector('#scroll-container');
const loadData = () => { /* 請(qǐng)求數(shù)據(jù)的操作 */ };
const throttledLoadData = throttle(loadData, 200);
scrollContainer.addEventListener('scroll', throttledLoadData);
通過(guò)這兩種技術(shù),我們可以有效地減少高頻率觸發(fā)事件的請(qǐng)求次數(shù),提高程序的性能。