how to send request after two second in angularjs on keyup event?

3232 views javascript
5

is there any way to send request to server after two 2 second when user stop typing in angularjs .something like debuncing .In other word if user type "abc" and stop wait for two seconds than hit to server .

currently whenever I type any character it request to server 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)
    });
    }
});

answered question

2 Answers

12

Use setTimeout function

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

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


$scope.keyupevt = function(){

  setTimeout(function(){

     $http.get("data.json").then(function(response) 
     {
       console.log(response)
     }
     )}, 2000);//delay parameter of 2 seconds

  }
});

posted this
8

Instead of setTimeout use $interval with angularjs as follows and use $interval.cancel() to cancel the request after one time,

  $scope.keyupevt = function() {
    var myInterval = $interval(function() {
        $http.get("data.json")
          .then(function(response) {
            console.log(response)
          });
      }, 2000, 1)
      .then(function() {
        $interval.cancel(myInterval);
      });
}

PLUNKER DEMO

posted this

Have an answer?

JD

Please login first before posting an answer.