In AngularJS, you use the $http service to make AJAX requests. When you initiate the AJAX request, you have to provide $http with a configuration object. One of the configuration options is "timeout". This option takes either a numeric value (milliseconds) or a promise. If the promise is resolved before the AJAX request has completed, AngularJS will call .abort() on the underlying XMLHttpRequest object.
NOTE: The timeout property only supports milliseconds and promises as of v1.2. Prior to that, the timeout option only supported milliseconds; meaning, there was no way to manually abort the underlying XMLHttpRequest object, even in v1.0.8.
As of late, I've been trying to create better encapsulation of the data persistence and retrieval mechanisms. This makes the matter a bit more complex because I don't want the calling context to have to worry about the $http service or about wiring up the timeout. To accomplish this, I have to create the deferred object and then inject it into the data response promise before I return it to the calling context. This way, the calling context can just call .abort() on the promise and the AJAX request will be aborted.
To see what I mean, take a look at the following code. The API in this demo (not shown) has a 5-second sleep() call to give us enough time to abort the request.
As you can see, after I've created the data-promise (as opposed to the AJAX-promise), I then augment it with an abort() method which will resolve the timeout.
The one big caveat to this approach is that if the calling context tries to invoke the .then() method on the resultant promise, the calling context will lose a handle on the .abort() method as it will be lost in the promise chain. This is why I am purposefully saving a reference to the primary promise before I hook into the resolution and rejection callbacks.
Aborting an AJAX request in AngularJS is not as easy as it is in jQuery. But, it's still possible; and, with enough encapsulation, you can still provide a simple interface for your data consumers. As a final note, I should also point out that $resource modules, as of v1.2, also provides a timeout option (though I have not yet tired it).
Want to use code from this post? Check out the license.