Search code examples
searchfilterangularjstimeoutdelay

How to put a delay on AngularJS instant search?


I have a performance issue that I can't seem to address. I have an instant search but it's somewhat laggy, since it starts searching on each keyup().

JS:

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

App.controller('DisplayController', function($scope, $http) {
$http.get('data.json').then(function(result){
    $scope.entries = result.data;
});
});

HTML:

<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:searchText">
<span>{{entry.content}}</span>
</div>

The JSON data isn't even that large, 300KB only, I think what I need to accomplish is to put a delay of ~1 sec on the search to wait for the user to finish typing, instead of performing the action on each keystroke. AngularJS does this internally, and after reading docs and other topics on here I couldn't find a specific answer.

I would appreciate any pointers on how I can delay the instant search.


Solution

  • (See answer below for a Angular 1.3 solution.)

    The issue here is that the search will execute every time the model changes, which is every keyup action on an input.

    There would be cleaner ways to do this, but probably the easiest way would be to switch the binding so that you have a $scope property defined inside your Controller on which your filter operates. That way you can control how frequently that $scope variable is updated. Something like this:

    JS:

    var App = angular.module('App', []);
    
    App.controller('DisplayController', function($scope, $http, $timeout) {
        $http.get('data.json').then(function(result){
            $scope.entries = result.data;
        });
    
        // This is what you will bind the filter to
        $scope.filterText = '';
    
        // Instantiate these variables outside the watch
        var tempFilterText = '',
            filterTextTimeout;
        $scope.$watch('searchText', function (val) {
            if (filterTextTimeout) $timeout.cancel(filterTextTimeout);
    
            tempFilterText = val;
            filterTextTimeout = $timeout(function() {
                $scope.filterText = tempFilterText;
            }, 250); // delay 250 ms
        })
    });
    

    HTML:

    <input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
    <div class="entry" ng-repeat="entry in entries | filter:filterText">
        <span>{{entry.content}}</span>
    </div>