Limit the Rate of Emissions from Observables with throttle in RxJS

André Staltz
InstructorAndré Staltz

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 2 years ago

Debounce is known to be a rate-limiting operator, but it's not the only one. This lessons introduces you to throttleTime and throttle, which only drop events (without delaying them) to accomplish rate limiting.

🚨 Since we are importing interval from RxJS, we don't need to preface our Observables with Rx.Observable. You can no longer .{operator}, you need to .pipe({operator}) instead.

[00:00] Debounce time is known to be a rate limiting operator, because if the rate of emission is once every 500 milliseconds, then it limits the rate to be one per second, which is less, but it's not the only rate limiting operator. There are others such as Throttle, for instance, throttleTime. ThrottleTime is comparable to debounceTime.

[00:22] While there is Throttle, which is comparable to Debounce. They work like Debounce but backwards. While Debounce waits for silence and then after the silence it emits, Throttle on the other hand first emits and then it causes silence to happen. Let's see how that works in a marble diagram.

[00:51] This is one second of silence. What it does when it sees zero, it will emit zero. It first emits and then it causes one second of silence. After it has caused that much, it can start emitting again. It emits two and then it causes that much of silence, and then it emits four, and then it would cause more silence, but it will just actually in this case complete. Let's just use it. The usage is similar to using bebounceTime.

[01:21] Just call throttleTime and give how much of silence do we want to cause. Then when we run this, we see zero, two, and four. So it really just sort of mirrored the input, but it limited the rate of emissions by having for sure this much of silence between these emissions.

[01:45] There are other rate limiting operators such as auditTime as well, but we don't need to go into detail with them. It's just important to know that if you want more strategies for rate limiting, you have different strategies.

[02:02] If you noticed, throttleTime is actually not a transformation operator. It's actually a filtering operator because as you can see, we could actually implement this case as filter. If you would filter if the number is even, you would get the same output here.

[02:22] That's just to say that throttleTime doesn't change these values. It doesn't move them in time. It just sort of drops some of these values. It doesn't do anything else than dropping. While Debounce had this Delay logic also. That's why Debounce is a transformation operator, but Throttle, its filtering operator that does rate limiting by just dropping some of these emissions.