Subscribe

Close

Thank you for visiting!

Please consider subscribing to the RSS feed or following me on Twitter.

Angular Delay with Debounce

Recently we were trying out a few things to delay validation of form fields in our Angular application. The not so good solution, was this:

<input type="text" ng-keyup="validate()" />

As soon as a keyboard key was released, the validate method was triggered. A little bit too often.

So we wanted something that created a delay in our validation. You could add a timeout handler in the validate function, but it wouldn't help, as the validate method would be called numerous times anyway, but with a delay.

In steps ng-change and ng-model-options with debounce. This is Angular 1.5.8. The new code that works really well:

<input type="text" ng-change="validate()" ng-model-options='{ debounce: 1000 }' />

This creates a delay of 1000 ms before the validate method is triggered.

Angular 2 version

Use RxJs Observables and the debounceTime() operator. Here's a good Stack Overflow thread on Angular 2 and debounceTime. In short, the pseudo code looks like this:

this.term.valueChanges
             .debounceTime(400)
             .subscribe(term => this.wikipediaService.search(term).then(items => this.items = items));

Further reading here.

To the top