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

2

2 Answers 2

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

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

Comments

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

2 Comments

This runs the function anyway just with a delay
In the question: "but if the value changes before the 300ms has gone, i need to reset the delay to 300ms".. well that's what the code does :)

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.