user944513
user944513

Reputation: 12729

how to send only one request instead of multiple request in angularjs?

I have a demo in which user type anything in input field and request goes to server. Currently whenever user type it fire the request. I want only one request will fire. Example if i type "abc" it fire three request. Is this possible user type anything without stop, after one sec stop I will fire a request.

i know Inputs can be debounced with the ng-model-options directive: but it fire after time given, but i want user type as long as without stop ,but fire request after stop

Here is my code:

http://plnkr.co/edit/npiA2abAo5SEQFMMpKZO?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,$http) {
   $scope.name = 'World';


    $scope.keyupevt = function(){
       console.log('xx')
       $http.get("data.json")
            .then(function(response) {
               console.log(response)
            });
    }
});

Upvotes: 2

Views: 967

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

Implement your own debouncing using setTimeout/clearTimeout, something like this will do:

app.controller('MainCtrl', function($scope,$http) {
    $scope.name = 'World';

    var timeout = null;                                // the timeout handle
    $scope.keyupevt = function() {
       clearTimeout(timeout);                          // clear any previous timeout (if null, nothing will happen)

       timeout = setTimeout(function() {               // set a new timeout
           console.log('xx');                          // that will make the request after 1 second
           $http.get("data.json")
             .then(function(response) {
               console.log(response);
           });
           timeout = null;                             // reset timeout (not really necessary but it won't do any harm)
       }, 1000);                                       // the code inside will be called after exactly 1000 ms
    }
});

Every time a key is down, a request will be set to happen after 1 second from that keydown event. And if the previous request didn't happen yet, the request will be cancelled and a new one will be set to happen after 1 second. etc

Upvotes: 1

Related Questions