RxJS Crash Course – Debounce and Throttle operators


Now let’s take a look at Debounce and throttle these two operators allow you to deal with events that you met way more values than you actually need.

RxJS Crash Course – Debounce and Throttle  operators
RxJS Crash Course – Debounce and Throttle operators

The mousemove event is a perfect example in the Dom.

Simple example

So, we’ll subscribe to the mouse event and then we’ll print the type of event here on the screen.

Let’s first do this without any throttling or debouncing you can see it only takes about two seconds to get hundreds of events printed here on the screen.

We can use the throttle to get the very first event and then set a delay before it starts emitting any other events.

Example of Throttle operator

In this case, we’ll use the throttle time helper and pass it 1000 milliseconds. So, now if we mouse over the screen we’ll get the first event. And then it will wait at least one second before sending any additional events.

Debounce example

Debounce does almost the same exact thing but instead of giving us the first event, it gives us the last event. So, first, we mouse over and there’s a delay then after that delay it will emit the most recent event.

Debounce is especially useful when you want to make sure the user is stopped doing something such as typing in an autocomplete form or something similar.

Let’s move to the next class.