jQuery-Autocomplete icon indicating copy to clipboard operation
jQuery-Autocomplete copied to clipboard

Use with API and debounce

Open invot opened this issue 10 years ago • 5 comments

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).

invot avatar Apr 18 '16 21:04 invot

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
});```

tkirda avatar Apr 19 '16 16:04 tkirda

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.

invot avatar Apr 21 '16 18:04 invot

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

tkirda avatar Apr 22 '16 15:04 tkirda

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 avatar Jul 29 '19 05:07 farizsofyan

@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.

tkirda avatar Aug 05 '19 11:08 tkirda