autocomplete icon indicating copy to clipboard operation
autocomplete copied to clipboard

Delay option

Open rafaelkapela opened this issue 7 years ago • 2 comments

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?

rafaelkapela avatar Jun 22 '18 17:06 rafaelkapela

I have the same question

roomoraaes avatar Jan 11 '19 11:01 roomoraaes

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={}])

pr0n1x avatar May 26 '21 08:05 pr0n1x