sf_tristanb
sf_tristanb

Reputation: 8855

jQuery : how to add a delay to an ajax request?

i have a function which returns a certain ammount of data triggered in AJAX when typping.

But, as soon as i type "long" string like "hello my name is", it launches a single request each time i type a key (10request at a single time and it takes 5 seconds to get 1 request response).

How to avoid that please ? (i don't want to use .onblur)

$(document).ready(function()
    {
      $('.search input[type="submit"]').hide();

      $('#search_keywords').keyup(function(key)
      {
        if (this.value.length >= 2 || this.value == '')
        {
          $('#loader').show();
          $('#jobs').load(
            $(this).parents('form').attr('action'),
            { query: this.value + '*' },
            function() { $('#loader').hide(); }
          );
        }
      });
    });

Thank you ;)

Upvotes: 2

Views: 1321

Answers (1)

Nick Craver
Nick Craver

Reputation: 630627

I tend to set a timer on that keyup event, like this:

$('#search_keywords').keyup(function() {
  clearTimeout($.data(this, 'timer'));
  $(this).data('timer', setTimeout($.proxy(search, this), 500));
});
function search()  {
  if (this.value.length >= 2 || this.value == '') {
    $('#loader').show();
    $('#jobs').load(
      $(this).parents('form').attr('action'),
      { query: this.value + '*' },
      function() { $('#loader').hide(); }
    );
  }
}

This breaks your search into another function, and we're just delaying 500ms between hitting a key and firing that search function. If you type another letter, the 500ms timer resets with the clearInterval(), so quick typing won't trigger 20 events, only once you pause a half second will it fire. The $.proxy() part is so that this is correct when the setTimeout() executes.

Upvotes: 6

Related Questions