开发者

Reduce amount of AJAX calls for autocomplete?

I was sending the AJAX query on the keyup for my search textbox but what I want to do is wait until 1 second after the user stops typing.

Code I have:

searchBar = $('#searchBar');
searchBar.timerID = null;
searchBar.textBox = $('#searchBar > input[name="q"]');
searchBar.textBox.开发者_运维问答sendQuery = function(){
  alert('SEND AJAX HERE');
  searchBar.timerID = null;
};
searchBar.textBox.keyup(function() {
  if(searchBar.timerID){ clearTimeout(searchBar.timerID); }
  searchBar.timerID = setTimeout(searchBar.textBox.sendQuery, 1000);
});

It seems to work, but is the the best way to about this?


This plugin will fire an event after a short delay. You could then use something like the following:

$(searchBar).bindWithDelay("keyup", callback, 1000);


It isn't good practise to be polluting the jQuery object returned like $('#searchBar').value = 'blah' -- instead you should ultilise the .data method:

You don't really need searchBar at all, just put the timer on the corresponding input element. I always prefix jQuery objects with $ for better clarification.

$input = $('#searchBar input[name="q"]');

var sendQuery = function() {
  alert('SEND AJAX HERE');
};

$input.keyup(function() {
  var timer = $(this).data('timerID');
  if (timer) {
      clearTimeout(timer);
  }
  $(this).data('timerID', setTimeout(sendQuery, 1000));
});


Look into Ben Alman's debounce plugin http://benalman.com/projects/jquery-throttle-debounce-plugin/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜