0

I'm building a angular directive, which on input value change runs a function, i want to wait 300ms before running this function, but if the value changes before the 300ms has gone, i need to reset the delay to 300ms. So only if value changes for 300ms then the function should run:

My code

(function() {
    'use strict';

    angular
    .module('address',[])
    .directive('address', ['Address', function (Address) {
      return {
        restrict: 'E',
        transclude: true,
        templateUrl: 'partials/address.html',
        link: function (scope, elem, attrs) {
            var delay = "300";
            scope.$watch('searchparam', function(){
                if(!_.isUndefined(scope.searchparam) && scope.searchparam.length >= 3) {
                    // here i need some delay timer
                    Address.get(scope.searchparam).then(function(data){
                        console.log("data: ", data);
                        scope.addressList = data;
                    }, function(status){
                        console.log("status: ", status);
                        scope.errorHandler = status;
                    });
                }
            }); 
        }
      };
    }]);
})();

The address.get is an async service that returns addresses

Simon Dragsbæk
  • 2,367
  • 3
  • 30
  • 53
  • possible duplicate of [How to write a debounce service in AngularJS](http://stackoverflow.com/questions/13320015/how-to-write-a-debounce-service-in-angularjs) – dting May 29 '15 at 12:58
  • didn't know it was called debouncing, but im trying to close – Simon Dragsbæk May 29 '15 at 13:17

2 Answers2

1

What you want to do is look into debouncing. It's included in most JS libraries.. and is standard as of AngularJS 1.3

Community
  • 1
  • 1
Alex McMillan
  • 17,096
  • 12
  • 55
  • 88
0

You need something like:

var delay = "300"; // not needed, just pointing where to put the rest of the code :)
var timeout;
scope.$watch('searchparam', function(){
    if(!_.isUndefined(scope.searchparam) && scope.searchparam.length >= 3) {
        function getAddress() {
            // do you stuff - Address.get(...
        }
        if (timeout) // try to clear the timeout if it was previously set
            clearTimeout(getAddress);
        timeout = setTimeout(getAddress, 300); // reset timer
Andrey Popov
  • 7,362
  • 4
  • 38
  • 58