具有延迟功能的输入触发器,如果​​输入值改变则等待

时间:2015-05-29 12:52:11

标签: javascript angularjs function

我正在构建一个角度指令,在输入值更改运行一个函数时,我想在运行此函数之前等待300ms,但如果值在300ms之前发生变化,我需要将延迟重置为300ms。因此,只有当值改变300ms时,该函数才会运行:

我的代码

(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;
                    });
                }
            }); 
        }
      };
    }]);
})();

address.get是一个返回地址的异步服务

2 个答案:

答案 0 :(得分:1)

您要做的是查看debouncing。它包含在大多数JS库中......并且是standard as of AngularJS 1.3

答案 1 :(得分:0)

您需要以下内容:

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