mustieles mustieles - 1 year ago 65
Ajax Question

How do I stop all ongoing Ajax calls in AngularJS

I'm making Ajax calls to an API triggered by an

event in a text input element.


<input type="text" ng-model="movieTitle" ng-change="writeTitle(movieTitle)">

The Javascript:

$scope.writeTitle = function(val){
val = val.replace(/ /g, "+");
var ajax_url = ''+val+'*';
$http.get(ajax_url).success(function(data) {
$scope.movies = data.Search;

What I want to do is, if someone types 4 characters in quick succession, only resolve the last Ajax call; otherwise they get mixed up sometimes and the user sees the result of a call other than the last one.

So, how do I stop ongoing Ajax calls whenever a new call is made and others are still on the queue?

Answer Source

The way you do this, is to limit how often you call a function, not by stopping further ajax calls per se.

The 2 common terms are either throttling or debouncing and with a H/T to this blog

Throttling - enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds.

Debouncing - enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called.

You can choose whichever is more appropriate for your situation, and implement it in your function.