1 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
將超時(shí) ID 存儲(chǔ)到高于您的事件監(jiān)聽器范圍內(nèi)的變量。當(dāng)事件觸發(fā)時(shí) - 檢查是否超時(shí)并清除它(這意味著如果尚未執(zhí)行則取消請求)
例子:
let delayedFetch;
lookup.addEventListener('keyup', e => {
let searchValue = e.target.value;
if (searchValue.length > 4){
if (delayedFetch) clearTimeout(delayedFetch);
delayedFetch = setTimeout(() => {
fetch(`{% url 'find_book' %}?param=${e.target.value}` )
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))}, 2000);
}
添加回答
舉報(bào)