Throttling enables you to disable input from an stream for a certain period of time, after first event. Example: You might want to call a submit button once - even after multiple clicks by a user. Or you might only want to call an api once after several keystrokes by user - as is case with "type as you search". Limiting API call on every user interaction saves you server side resources and also enhance user experience.
You can either disable the button or field from taking in more user inputs. But that's not elegant.
Better way would be to create stream of event for every user interaction and then apply plethora of operators that RxJs provides. Most important operator would be "throttleTime". Below is an example, using angular.
In HTML file a subject has been created that launches event - "submit" on every button click. On component (TS) side, this stream is throttled and post that onSubmit()
process is called.
Note that writing: <button type="button" (click)="onSubmit()" class="btn btn-primary">Save changes</button>
and in onSubmit calling:
onSubmit() {
if (this.messageForm.valid) {
const group_id = this.groupDetails.id;
if (group_id) {
const formObject = this.messageForm.value;
formObject.group_id = group_id;
this.templateService
.createNewMessage(formObject)
.subscribe({
next: res => {
this.closeModal();
this.messageForm.reset({
title: "",
message_type: "text",
option_type: "na",
message_by: "bot"
});
this.templateService.refreshMessageList();
this.toaster.Success("Message added successfully");
}
});
}
}
}
This WOULDN'T have worked as on every button click - onSubmit would have created a separate stream, on which throttle would not work. As throttling is practically possible on a continuous stream and can't be applied on every new stream.