gpt4 book ai didi

javascript - 如何延迟/开始/去抖动获取数据直到用户停止输入?

转载 作者:搜寻专家 更新时间:2023-10-31 23:56:52 25 4
gpt4 key购买 nike

如果我的应用程序有足够多的用户,每次击键时发送一个 ajax 请求是使服务器崩溃的有效方法(更不用说可能使客户端应用程序感觉非常缓慢)。实现带有两个选项(DB 搜索和 Web Api 搜索)的符号搜索框。当我在搜索框中键入符号(例如:AAPL - aple stock)时,每次都会通过网络发送 fetch() 请求。为了避免这种情况,我尝试使用 setTimeout()fetch() 请求无论如何都会被发送多次。如何延迟/开始/反跳获取请求,直到用户停止在输入区域中键入以仅发送一个 fetch() 请求?

HTML:

<label for="symbolTags">Symbol: </label>
<input type="text" id="symbolTags" name="symbol">

<label for="api">Select Search Api: </label>
<select id="api" name="routes_api">
<option value="search">Web Search Api</option>
<option value="dbsearch">DB Search Api</option>
</select>

JavaScript:

const symbolTags = document.querySelector('#symbolTags')
const symbolTagsOptions = document.querySelector('#api')

const urlsObject = {
dbsearch: '/dbsearch/',
search: '/search/'
}

symbolTags.oninput = function () {
let symbolTagsOptionsValue = symbolTagsOptions.value
let arg = urlsObject[symbolTagsOptionsValue]

// Init a timeout variable to be used below
let timeout = null
// Clear the timeout if it has already been set.
// This will prevent the previous task from executing
// if it has been less than <MILLISECONDS>
clearTimeout(timeout)
// Make a new timeout set to go off in 2000ms
timeout = setTimeout(function () {
requestSymbolSearch(arg)
}, 2000)
}

function requestSymbolSearch(arg) {
getData(arg)
.then(data => {
console.log(data)
$('#symbolTags').autocomplete({
source: data.map(item => item.symbol),
autoFocus: true
})
})
.catch(error => console.error('Error:', error))
}

function getData(url) {
let curValueSymbol = symbolTags.value
let urlPlus = `${url}${curValueSymbol}`
console.log(urlPlus)
return fetchData(urlPlus)
}

async function fetchData(urlPlus) {
const dataResponse = await fetch(urlPlus)
const dataJson = await dataResponse.json()
return dataJson
}

控制台结果如下:

fetch result

这是网络结果:

enter image description here

最佳答案

这通常由 debouncing 解决 事件;将给定时间范围内的多个调用折叠为一个:

// Debounce function from: https://stackoverflow.com/q/24004791/1814486
const debounce = (func, wait, immediate) => {
let timeout

return function() {
const context = this, args = arguments
const later = function() {
timeout = null
if (!immediate) func.apply(context, args)
}

const callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}

// If there's not another `input` within 500ms log the value,
// otherwise ignore the event.
document.querySelector('#input').addEventListener('input', debounce(() => {
console.log(input.value)
}, 500))
<input id="input" placeholder="Type fast here.."/>

关于javascript - 如何延迟/开始/去抖动获取数据直到用户停止输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54301090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com