1

I have an input field. When there is a keyup on this field, I send a request . My problem is when another keyup event is triggered, I need to cancel all pending requests. I have seen a lot of answers, but I have not found a solution.

var data = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        wildcard: '%QUERY',
        url: $('.typeahead').attr('data-autocomplete-url') + '?term=%QUERY',
        rateLimitBy: 'throttle',
        ajax: {
            async: true,
            dataType: 'json',
            crossDomain: true,
        }
    }

});

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
},{
    name: 'company',
    displayKey: 'id',
    limit: Infinity,
    source: data,
    templates: {
        empty: [
            '<div style="margin: 4px 30px 4px 30px;" class="empty-message">',
            '  Aucun résultat trouvé   ',
            '</div>'
        ].join('\n'),
        suggestion: function(data) {
            if(data.id_db == 'more'){
                return '<p style="pointer-events:none">'+ data.text +'</p>';
            }else{
                return '<p>'+ data.text +'</p>';
            }

        }
    }
}).on('typeahead:select', function(ev, data) {
    $('#id_db').val(data.id_db);
    changeCompany($(this));
});
tr.am
  • 295
  • 1
  • 3
  • 11
  • You can change your remote settings a little and acchieve what you want using abort() function. See my answer here: https://stackoverflow.com/a/46959188/3638529 – joalcego Oct 26 '17 at 16:19

2 Answers2

1

This is a trick I use. clearTimeout cancels the previous event. So only after the client stops typing for 400 ms, the Ajax call will be made.

(I don't know typeahead, so use whatever event handling that it requires...)

var timer;
$('.typeahead').on('keyup', function(e) {
  clearTimeout(timer);
  timer = setTimeout(function() {
      $.ajax({
        ...
      });
    },
    400   // Guestimate the best value you want, usually I use 300 - 400 ms
  )
});
Emmanuel Delay
  • 3,619
  • 1
  • 11
  • 17
0
var cancelprev = null;
$("#typhead").typeahead({
    source: function(query, process) {
        var searchval = $('#searchval').val();
        
        
            if (cancelprev != null) 
           cancelprev.abort();
       
       
        var defered=$.get(requesturl,{data:searchval}).done(function(result){
            process(result.split("\n"));
        });
        
        cancelprev=defered;
    }
    
});