0

I have a situation where I can't use debounce in html like ng-model-option: {debounce:1000}

But I want to remove repeated callbacks to function doCallback in my directive, and make only 1 call in 1s

html: <input ng-change="vm.GetStuff">

angular directive:

class SuperDirective {
    eventTime: any;
    anotherCallWasMade: boolean;

  static $inject = ['$scope', "$timeout"];
  constructor($scope: angular.IScope, $timeout: ng.ITimeoutService) {
            super();
...
      }



   GetStuff(): void {

          //I've tried something like this but it didn't exactly work             
          if (this.eventTime == undefined) {
                this.eventTime = Date.now();
                this.anotherCallWasMade = true;
            } else {
                var currentTime = Date.now().valueOf();
                var eventTime = this.eventTime.valueOf();
                var sec = (Date.now().valueOf() - this.eventTime.valueOf())/1000;
                if (sec <= 1) {
                //If this is the first attempt after original request then we perform a search once more, if this is another request during the same second we dont do anything..
                    if (this.anotherCallWasMade) {
                        this.anotherCallWasMade = false;
                        this.$timeout(() => {
                            this.eventTime = Date.now();
                            this.get_Items();
                        }, 1000);
                    }
                    return;
                }
                this.anotherCallWasMade = true;
                this.eventTime = Date.now();
            }

                this.$timeout(() => {
                    if (this.doCallback != null) {
                        // I want to call this once in 1s instead of multiple times 
                        this.doCallback ();
                    }
                }, 0);

            }
        }

maybe there is an easier way to remove unnessesary calls to this.doCallback() ?

Greeed
  • 418
  • 2
  • 8
  • 29
  • What is actually making the calls to this function? – Mike Feltman May 17 '16 at 13:16
  • @Mike Feltman GetStuff()is called whenever a change is made to the input/search field. and This.doCallback is called by angular I assume, export function SuperDirective() { return { restrict: 'E', scope: { doCallback : "&?"... – Greeed May 17 '16 at 13:29
  • Solved the problem, the issue was that I was making too many calls, and sometimes when the timeout was called a few searches before the timeout call one have happened and messed up the timers... – Greeed May 17 '16 at 14:25

0 Answers0