2

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)
            });
    }
});
1
  • you could have it fire if you lose focus and input > 0. You could also have a minimum character limit and wait until you at least hit that before sending a request. Commented Nov 4, 2018 at 23:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.