在前端中可以使用防抖(debounce)和节流(throttle)来避免每次输入变化都发送网络请求。具体的实现可以参考以下代码示例:
防抖(debounce):
function debounce(callback, delay) {
let timeoutId = null;
return function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback.apply(this, arguments);
}, delay);
};
}
const input = document.getElementById('input');
input.addEventListener('input', debounce(() => {
// 发送网络请求的逻辑
}, 300));
节流(throttle):
function throttle(callback, delay) {
let timerId = null;
let lastExecTime = 0;
return function() {
const now = Date.now();
const elapsed = now - lastExecTime;
if (!timerId && elapsed >= delay) {
callback.apply(this, arguments);
lastExecTime = now;
} else {
clearTimeout(timerId);
timerId = setTimeout(() => {
callback.apply(this, arguments);
lastExecTime = Date.now();
timerId = null;
}, delay - elapsed);
}
}
}
const input = document.getElementById('input');
input.addEventListener('input', throttle(() => {
// 发送网络请求的逻辑
}, 300));