⚠️ This lesson is retired and might contain outdated information.

Debounce the user input in Angular 2 using debounceTime

Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 9 months ago

In this video we'll learn how to use the debounceTime operator to tame the user input for an instant search.

[00:00] Now that we consumed the input event of our text box as an observable, we can apply a whole set of AX operators on top of it to create a more meaningful observable for our specific use case.

[00:10] When we look at the network type of our browser, we will notice that we currently make requests to the Wikipedia API with every single keystroke. In a real-world scenario, we wouldn't like to hammer our server like this, and rather be more economical with our resources.

[00:25] What we actually want is to make requests whenever the user stopped typing for a brief moment. In technical terms, that means skip all the notifications up to the point where there hasn't been a new notification for at least say, 400 milliseconds. Once we have that gap, that the last notification comes through.

[00:44] The good news is there's AX operator for exactly that behavior, and it's called debounceTime. Let's turn back to our code and first import the operator. We do that right off of the import that we did for the map operator.

[00:56] Since they are all shared across the application, we can leave them right here. What we do is we apply the debounceTime operator on top of our term observable. This doesn't directly modify the term observable. Instead, it creates a completely new observable that has the desired behavior.

[01:13] Let's check out the network type of our browser again, and see the difference. We can clearly see that we don't perform request on every keystroke anymore. The requests go out as soon I rest my fingers for a brief moment, which is exactly what we want.

Michael
Michael
~ 8 years ago

you can find out the demo code from author's website: http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html#demos

lucb202
lucb202
~ 5 years ago

I just subscribed to EggHead to be able to understand this better, but it seems like this video series is out of date. Can anything be updated so that it makes my subscription worth the money?

Markdown supported.
Become a member to join the discussionEnroll Today