xdan / autocomplete

jQuery autocomplete plugin like Google autocomplete
MIT License
256 stars 92 forks source link

Delay option #41

Open rafaelkapela opened 6 years ago

rafaelkapela commented 6 years ago

How to set delay option? Currently for every character it is calling the rest api. I want to set delay option to reduce the api calls, but how?

roomoraaes commented 5 years ago

I have the same question

pr0n1x commented 3 years ago

You can do it manually like code bellow

const $input = $(".header-search__input");
const suggestUrl = $input.data('suggest-url');
if (!suggestUrl) return;
const inputDelay = 400;
let inputDelayTimeoutId = 0;
$input.autocomplete({
  appendMethod:'replace',
  source:[
    function(q, add) {
      if (!q) return;
      if (inputDelayTimeoutId) clearTimeout(inputDelayTimeoutId);
      const query = `${suggestUrl}?q=${q}`;
      console.log('type:', q);
      inputDelayTimeoutId = setTimeout(function() {
        console.log('query', query);
        $.getJSON(query, function(suggestions) {
          if (typeof suggestions.items === 'object'
            && Array.isArray(suggestions.items)
            && suggestions.items.length > 0
          ) {
            const suggestionStrings = suggestions.items.reduce(function(result, item) {
              result.push(item.title);
              return result;
            }, []);
            console.log('set suggestions', suggestionStrings);
            add(suggestionStrings);
          }
        });
      }, inputDelay)
    }
  ]
});

Also you can use https://lodash.com/docs/#debounce

_.debounce(func, [wait=0], [options={}])