Friday, May 16, 2014

consolidate Ajax Call

Suppose there is an ajax call which is issued each time when user is typing a character in a text box. If the end user types 10 characters, there will be 10 ajax call. However, only the result from last one is used by application. It is really wasteful to make the other 9 calls.

Here is one approach how you can cancel the uncessary ajax call. I am using $timeout service in angularjs. You can use standard timeout API.

$scope.ajaxcall=null;

if ($scope.ajaxcall!==null) {
 $timeout.cancel($scope.ajaxcall);
}
$scope.ajaxcall=$timeout(function() {
// my ajaxcall here
}, 300);


Here is all ajax call is queued by timeout. If the next call found an invoked call, it cancels the previous one. Of course, if the call is already made, the cancellation has no effects. If the end user types rapidly and do not care the intermediate results, you can cancel most of the unnecessary ajax call.


No comments:

Post a Comment