JavaScript接口防止重復(fù)請(qǐng)求的方法總結(jié)
摘要:
在前端開發(fā)中,防止重復(fù)請(qǐng)求是一個(gè)常見的問題。重復(fù)請(qǐng)求不僅會(huì)增加服務(wù)器的負(fù)載,還可能導(dǎo)致數(shù)據(jù)不一致等問題!
1、使用防抖(Debounce)或節(jié)流(Throttle)
防抖(Debounce):在用戶停止觸發(fā)某個(gè)事件一定時(shí)間后執(zhí)行函數(shù)。例如,用戶頻繁點(diǎn)擊按鈕時(shí),只有最后一次點(diǎn)擊會(huì)觸發(fā)請(qǐng)求。
function debounce(func, wait) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
// 使用方法
const debouncedFetch = debounce((url) => fetch(url), 300);
debouncedFetch('https://api.example.com/data');節(jié)流(Throttle):規(guī)定在一個(gè)單位時(shí)間內(nèi),只能觸發(fā)一次函數(shù)執(zhí)行。如果在同一個(gè)單位時(shí)間內(nèi)多次觸發(fā)函數(shù),只有一次生效。
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if (Date.now() - lastRan >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
???????// 使用方法
const throttledFetch = throttle((url) => fetch(url), 2000);
throttledFetch('https://api.example.com/data');2、使用標(biāo)志位(Flag)來防止重復(fù)請(qǐng)求
通過設(shè)置一個(gè)標(biāo)志位,在請(qǐng)求進(jìn)行中時(shí)阻止后續(xù)請(qǐng)求。
let isFetching = false;
function fetchData(url) {
if (isFetching) return;
isFetching = true;
??????? fetch(url)
.then(response => response.json())
.then(data => {
// 處理返回的數(shù)據(jù)
})
.catch(error => {
console.error('Error:', error);
})
.finally(() => {
isFetching = false;
});
}3、使用 AbortController
AbortController 允許你在需要的時(shí)候中止請(qǐng)求。
const controller = new AbortController();
const signal = controller.signal;
function fetchData(url) {
fetch(url, { signal })
.then(response => response.json())
.then(data => {
// 處理返回的數(shù)據(jù)
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Error:', error);
}
});
}
???????// 在需要中止請(qǐng)求的地方調(diào)用 controller.abort()
controller.abort();4、使用第三方庫(如 Axios 和 Redux-Saga)
如果你在使用 Axios 或 Redux-Saga,可以利用這些庫提供的中間件功能來實(shí)現(xiàn)防止重復(fù)請(qǐng)求。
Axios Cancel Token
Axios 支持取消請(qǐng)求的功能,可以通過 CancelToken 實(shí)現(xiàn)。
const axios = require('axios');
const CancelToken = axios.CancelToken;
let cancel;
???????function fetchData(url) {
if (cancel) {
cancel('Operation canceled due to new request.');
}
cancel = null;
const source = CancelToken.source();
axios.get(url, { cancelToken: source.token })
.then(response => {
// 處理返回的數(shù)據(jù)
})
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
console.error('Error:', thrown);
}
});
}總結(jié)
以上是幾種常見的防止重復(fù)請(qǐng)求的方法,可以根據(jù)具體場(chǎng)景選擇合適的方法。防抖和節(jié)流適用于頻繁觸發(fā)的事件,標(biāo)志位和 AbortController 適用于需要手動(dòng)控制請(qǐng)求的情況,而第三方庫則提供了更強(qiáng)大的功能和靈活性。
到此這篇關(guān)于JavaScript接口防止重復(fù)請(qǐng)求的方法總結(jié)的文章就介紹到這了,更多相關(guān)JavaScript接口防止重復(fù)請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
three.js中3D視野的縮放實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了three.js中3D視野的縮放實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
基于JavaScript中標(biāo)識(shí)符的命名規(guī)則介紹
下面小編就為大家分享一篇基于JavaScript中標(biāo)識(shí)符的命名規(guī)則介紹,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-01-01
security.js實(shí)現(xiàn)的RSA加密功能示例
這篇文章主要介紹了security.js實(shí)現(xiàn)的RSA加密功能,結(jié)合實(shí)例形式分析了基于security.js進(jìn)行RSA加密的相關(guān)操作技巧,需要的朋友可以參考下2018-06-06
setTimeout 函數(shù)在前端延遲搜索實(shí)現(xiàn)中的作用詳解
這篇文章主要為大家介紹了setTimeout 函數(shù)在前端延遲搜索實(shí)現(xiàn)中的作用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
JavaScript在for循環(huán)中綁定事件解決事件參數(shù)不同的情況
響應(yīng)一堆相似的事件,但是每個(gè)事件的參數(shù)都不同,在這種情況下就可以使用JavaScript 在for循環(huán)中綁定事件,下面有個(gè)不錯(cuò)的示例,大家可以參考下2014-01-01

