title: Abort new AJAX request before completing the previous one
body: <p>I have a function that runs an AJAX call on the change of an input.</p>
  <p>But, there is a chance that the function will be fired again before the previous ajax call has completed.</p>
  <p>My question is, how would I abort the previous AJAX call before starting a new one?
  Without using a global variable. (See answer to a similar question <a href="https://stackoverflow.com/questions/4551175/how-to-cancel-abort-jquery-ajax-request">here</a>)</p>
  <p><a href="https://jsfiddle.net/YzDBg/" rel="nofollow noreferrer">JSFiddle</a> of my current code:</p>
  <p><strong>Javascript:</strong></p>
  <pre><code>var filterCandidates = function(form){
      //Previous request needs to be aborted.
      var request = $.ajax({
          type: 'POST',
          url: '/echo/json/',
          data: {
              json: JSON.stringify({
                  count: 1
              })
          },
          success: function(data){
              if(typeof data !== 'undefined'){
                  jQuery('.count').text(data.count)
                  console.log(data.count);
              }
          }
      });
  };
  
  if(jQuery('#search').length &gt; 0){
      var form = jQuery('#search');
      jQuery(form).find(':input').change(function() {
          filterCandidates(form);
      });
      filterCandidates(form);
  }
  </code></pre>
  <p><strong>HTML:</strong></p>
  <pre><code>&lt;form id=&quot;search&quot; name=&quot;search&quot;&gt;
      &lt;input name=&quot;test&quot; type=&quot;text&quot; /&gt;
      &lt;input name=&quot;testtwo&quot; type=&quot;text&quot; /&gt;
  &lt;/form&gt;
  &lt;span class=&quot;count&quot;&gt;&lt;/span&gt;
  </code></pre>