title: I have too many AJAX requests
body: <p>A bit of an advanced question here (for a noob like me haha). I am writing an app that makes AJAX requests when I click on a navigation item to show up content relevant for that navigation item. So far so good. One request per click, thats fine.</p>
  
  <p>The problem arises when I make AJAX requests through the JS that is retrieved by the first AJAX request, the one from the navigation item. A sort of inception if you will. A request within a request o.O</p>
  
  <p>The code I am presenting to you has the job of retrieving data when a key is up, after a specified delay. The problem is, that even though there is a delay, a request is made for every key pressed. How do I reduce the number of requests?</p>
  
  <pre><code>var delay = (function(){
        var timer = 0;
        return function(callback, ms){
          clearTimeout (timer);
          timer = setTimeout(callback, ms);
        };
      })();
  
  $("#browse-foods-search-input").keyup(function(){
      delay(function(){ 
  
          // This IF checks if the field is empty. If so, the default content is loaded
          if ($("#browse-foods-search-input").val() == "")
          {
              $.ajax({
                  type: "GET",
                  url: "ajaxLoad.php?action=food-journal&amp;mod=browse-foods&amp;send_header=0",
                  success: function(response) {
                      $(".browse-foods-container").html(response.html);
                      eval($(response.js).text());                           
                  }
              });
          }
          else {    // This ELSE creates the request for searching
             $.ajax({
                 type: "GET",
                 url: "ajaxLoad.php?action=food-journal&amp;mod=browse-foods&amp;search_key="+$("#browse-foods-search-input").val(),
                 success: function(response) {
                      $(".browse-foods-container").html(response.html);
                      eval($(response.js).text());
                 }
               });   
          }   
      }, 500 );        
  });  
  </code></pre>
  
  <p>Please note that the above code works as intended, but I am interested in optimizing my code. Any questions, comments, criticisism are welcome!</p>