Search code examples
javascriptangularjsdelay

how to daly send request after user stop typing using angularjs


I am trying to find away to delay send request to WebApi after user stop typing using Angularjs 500 or 800 millisecond right now my code will send what user type and query data. I am thinking to delay send request but I don't know how to do it

                <label for="exampleInputEmail1">search</label>
                <input type="search" class="form-control user-search" data-ng-model="searchString" ng-keyup="search()" placeholder="Enter search here">
<div class="row">
    <div ng-repeat="user in users" class="col-xs-6 col-lg-4">
        <div>
            <h3>{{user.FName +' '+ user.LName }}</h3>
            <p>{{user.Title}}</p>

        </div>

HomeController

(function () {
    'use strict';

    var app = angular.module('finduser');

    var HomeController = function($scope, homeService) {

        $scope.searchString = "";
        $scope.currentPage = 1;

        var getUsers = function(searchString) {
            if (searchString) {
                homeService.getUsers(searchString).then(function(data) {
                    $scope.users = data;
                }, function(errMsg) {
                    console.log(errMsg);
                });
            }
        } // /getUsers


    //search user                  
        $scope.search = function () {
            if ($scope.searchString.length >= 2) {
                getUsers($scope.searchString);
            }
        };// /search

    };// /HomeController


    app.controller('HomeController', ['$scope', 'HomeService', HomeController]);

}());

Home Service

(function () {
    'use strict';

    var app = angular.module('finduser');

    var HomeService = function ($http) {

        var getUsers = function (search) {
            var str = search.replace('.', '~');
            var uri = 'api/values?value=' + encodeURIComponent(str);

            return $http.get(uri).then(function (response) {
                return response.data;
            });
        };

        return {
            getUsers: getUsers
        };
    };

    app.factory('HomeService', ['$http', HomeService]);
}());

Solution

  • Your decision to delay (or "debounce," as this technique is sometimes called) is wise--if you get enough users on your application, sending an ajax request with each keystroke is an effective way to bring your server to its knees (not to mention possibly making your client application feel quite sluggish).

    The trick is clearing the timeout when you receive another keystroke event. That way only when the user stops typing the timeout will have a chance to complete. Consider this example:

    var timeoutPromise;
    $scope.search = function() {
      $timeout.cancel(timeoutPromise);
      timeoutPromise = $timeout(function() {
        // Make your API request here...
      }, 800);
    };