0

I wanted to reuse my working jQuery function in Angular which has two functions, one called on keyup other on keydown

<input type="text" [(ngModel)]="filterOptions.SearchValue" (keyup)="onFilter($event)" (keydown)="resetCounter()" class="form-control">

So that the counter gets reset every time on keydown. However this doesn't work:

timer = 0;

onFilter(event: any) {
    if (!HelperService.keypressFilter(event))
        return;

    console.log(this.timer);

    clearTimeout(this.timer);
    this.timer = setTimeout(this.resetValues(), 2000);
}

resetCounter(){
    console.log(this.timer);
    clearTimeout(this.timer);
    console.log(this.timer);
}

Each of the 3 console logs write the same number in the console, and they do so incrementally (i.e. 0 0 0, 3 3 3, 24 24 24...) after each key press. Those numbers have nothing to do with milliseconds. How can I make it work?

Norgul
  • 4,613
  • 13
  • 61
  • 144
  • The numbers of `this.timeout` are for javascript and do not mean milliseconds. Just add `this.filterOptions.SearchValue = ""` before `clearTimeout` in `resetCounter()` and it should work. Let me know if it doesn't. – Dhyey Jul 18 '17 at 13:14
  • that just clears the input field and I can't enter more than one letter because it deletes it – Norgul Jul 18 '17 at 13:31
  • This is basically a duplicate of: https://stackoverflow.com/questions/32051273/angular2-and-debounce – mcgraphix Jul 18 '17 at 16:27
  • I found a simpler solution, I'll post it – Norgul Jul 19 '17 at 07:58

1 Answers1

-3

So the solution was to utilize Angular setTimeout() function:

timer: any;

onFilter(event: any) {
    if (!HelperService.keypressFilter(event))
        return;

    clearTimeout(this.timer);
    this.timer = setTimeout(() => { this.resetValues() }, 200)
}

resetCounter() {
    clearTimeout(this.timer);
}
Norgul
  • 4,613
  • 13
  • 61
  • 144