Need help to delay 2 seconds before sending json request

Need help to delay 2 seconds before sending json request

Below is my script. It's a autosuggestion search script. The problem is that it penetrates the server with a huge amount of requests (it sends a request after each inserted character).

I need to change the script so that it waits 2 seconds after user has finished typing (and has inserted at least 3 characters) and only then sends request to the php file.

  1. (function($){
  2. $.fn.fsearch = function(){
  3. var $searchInput = $(this);
  4. $searchInput.after('<div id="divResult"></div>');
  5. $resultDiv = $('#divResult');
  6. $searchInput.focus();
  7. $searchInput.addClass('searchi');
  8. $resultDiv.html("<ul></ul><div id='search-footer' class='searchf'></div>");
  9. $searchInput.keyup(function(e) {
  10. var q=$(this).val();
  11. if(q.length>2&&q.length<30){
  12. var current_index = $('.selected').index(),
  13. $options = $resultDiv.find('.option'),
  14. items_total = $options.length;
  15. $resultDiv.fadeIn();
  16. $resultDiv.find('#search-footer').html("<img src='img/loader.gif' alt='Searching...'/>");
  17. $.getJSON("/search.php",{searchword: q},function(jsonResult) {
  18. var str='';
  19. for(var i=0; i<jsonResult.length;i++)
  20. {
  21. str += '<li id=' + jsonResult[i].uid + ' class="option"><img class="profile_image" src="photos/'+jsonResult[i].media+'" alt="'+jsonResult[i].username+'"/><span class="name">' + jsonResult[i].username + '</span><br/>'+jsonResult[i].country+'</li>';
  22. }
  23. $resultDiv.find('ul').empty().prepend(str);
  24. $resultDiv.find('div#search-footer').text(jsonResult.length + " results found...");
  25. $resultDiv.find('ul li').first().addClass('selected');
  26. });
  27. $resultDiv.find('ul li').live('mouseover',function(e){
  28. current_index = $resultDiv.find('ul li').index(this);
  29. $options = $resultDiv.find('.option');
  30. change_selection($options,current_index);
  31. });
  32. function change_selection($options,current_index){
  33. $options.removeClass('selected');
  34. $options.eq(current_index).addClass('selected');
  35. }
  36. } else{
  37. $resultDiv.hide();
  38. }
  39. });
  40. jQuery(document).live("click", function(e) {
  41. var $clicked = $(e.target);
  42. if ($clicked.hasClass("searchi") || $clicked.hasClass("searchf")){
  43. }
  44. else{
  45. $resultDiv.fadeOut();
  46. }
  47. });
  48. $searchInput.click(function(){
  49. var q=$(this).val();
  50. if(q.length>2&&q.length<30) {
  51. $resultDiv.fadeIn();
  52. }
  53. });
  54. $resultDiv.find('li').live("click",function(e){
  55. var id = $(this).attr('id');
  56. var name = ($(this).find('.name').text());
  57. $searchInput.val(name);
  58. });
  59. };
  60. })(jQuery);