要解决“Ajax请求数量不断增加”的问题,可以采取以下方法:
防抖:在一定时间内,如果连续触发同一事件,则只执行一次请求。 代码示例:
function debounce(func, delay) {
let timer;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
func.apply(context, args);
}, delay);
};
}
// 在Ajax请求的地方使用防抖函数
const debouncedAjaxRequest = debounce(ajaxRequest, 500); // 延迟500ms执行请求
element.addEventListener('click', debouncedAjaxRequest);
节流:在一定时间内,按固定频率执行请求,比如每隔500ms执行一次请求。 代码示例:
function throttle(func, delay) {
let timer;
let lastExecTime = 0;
return function() {
const context = this;
const args = arguments;
const now = Date.now();
if (now - lastExecTime >= delay) {
func.apply(context, args);
lastExecTime = now;
} else {
clearTimeout(timer);
timer = setTimeout(function() {
func.apply(context, args);
lastExecTime = now;
}, delay);
}
};
}
// 在Ajax请求的地方使用节流函数
const throttledAjaxRequest = throttle(ajaxRequest, 500); // 每隔500ms执行一次请求
element.addEventListener('click', throttledAjaxRequest);
代码示例:
let isRequesting = false;
function ajaxRequest() {
if (isRequesting) {
return;
}
isRequesting = true;
// 发起Ajax请求
// ...
// 请求返回后将标志位设为false
isRequesting = false;
}
element.addEventListener('click', ajaxRequest);
通过以上方法,可以有效控制Ajax请求数量不断增加的问题。