Use with API and debounce
I have an API that I would like to limit the lookups for. I know I can set minChars to limit these requests, but is there a way to have it only perform lookups every 600ms or so? This would help me reduce API calls drastically.
My current code looks like this:
$('input[data-cities]').autocomplete({
lookup:function(query,done){
r = loadAPI(query,'mysite.com/api/cities'); // function that returns a list of cities
done(r);
},
minChars:3
});
I would like to set a debounce so that the list doesn't update with every keypress. It seems like wrapping any part of that code in a setTimeout or anything similar doesn't do the trick (things just stop working).
You should be able to use debounced function:
https://lodash.com/docs#debounce
var loadAPIdeboundced = _.debounce(function (query, endpoint, done) {
var r = loadAPI(query, endpoint);
done(r);
}, 200);
$('input[data-cities]').autocomplete({
lookup:function(query,done){
loadAPIdeboundced(query,'mysite.com/api/cities', done);
},
minChars:3
});```
Thank you for your response! But... is there a way to do this with jQuery or vanilla? I don't want to import a whole library just for this one instance.
You can easily just take that single function from lodash https://www.npmjs.com/package/lodash.debounce
Or find other implementation: https://www.npmjs.com/search?q=debounce
Thanks for debounce solution @tkirda
i found out if we use lookUp solution above, preventBadQueries won't working. Is there any way to use debounce and keep preventBadQueries working?
@farizsofyan in this case lookup logic should be fully managed by provided function. To support what you asking, update is needed. This project is in maintenance mode and this most likely will not be implemented.