SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

Cancellable Deferred

Cancellable Operations

Extend a Deferred with a cancel method to support cancellation — useful for search-as-you-type where stale requests should be ignored.

Example
let currentRequest = null;

$("#search").on("input", function() {
  if (currentRequest) currentRequest.abort();

  const q = $(this).val();
  currentRequest = $.getJSON("/api/search?q=" + q)
    .done(function(results) {
      renderResults(results);
    })
    .always(function() {
      currentRequest = null;
    });
});
Pro Tip

Aborting stale XHR requests prevents out-of-order responses from corrupting the UI.