This is Jerry’s 11th article in 2021, and the 282nd original article on Wang zixi’s official account.

Jerry’s previous article SAP UI5 OData rumor crusher: Send two OData requests in a very short time, will the first one be automatically cancelled? It introduced a Live Search scenario developed by CRM Fiori development team of SAP Chengdu Research Institute.

The user creates Opportunity, maintains the Account field, and fires the SAP UI5 Input control’s liveChange event for each character entered. In onAccountInputFieldChanged processing function of the event, according to user input, send OData query request to the background.

If the user enters quickly, multiple OData requests can be sent to the background in a short period of time, resulting in the OData request being cancelled as described in Jerry’s article.

Recently Jerry was working on SAP Spartacus development and came across the same scenario. So in this article, I summarize what I’ve learned recently and document how SAP UI5 and Angular use Debounce and Throttle functions to avoid triggering frequent function calls in a short period of time.

For the sake of illustration, Jerry made an SAP UI5 page with just one Input control. Source code address.

Typing a character in the Input will trigger a liveChange event that sends the latest content of the current Input to a backend service I developed myself. The background service does nothing but simply returns the received content to the UI.

The liveChange event handling for the Input control in the SAP UI5 page is as follows:

According to the Chrome console print, I typed 1,234 characters in quick succession in one second, resulting in four requests to the background.

How does SAP UI5 use Debounce to reduce the frequency of function calls

The term “Debounce,” originally derived from mechanical switches and relays, combines multiple signals into a single signal.

Imagine a scenario we all encounter in real life: getting into an elevator. Elevators have an automatic closing timeout, let’s say 2 seconds. When the elevator detects someone entering, it resets the two-second timer. If no new passengers enter the elevator within the next two seconds, the doors will automatically close.

The elevator closing delay scenario is a typical practical example of function shock prevention. The elevator closing behavior is the “function”, through the automatic closing timeout of the elevator door, 2 seconds, to delay the execution of the closing action of the elevator door, so as to reduce the closing frequency of the elevator door, this is the “shake”.

It can be imagined that if the automatic closing of the elevator door does not set a timeout time, but immediately closes after no one is detected in and out, which will greatly increase the frequency of the elevator door opening and closing, which wastes energy and is not safe. This is like the example Jerry mentioned at the beginning of this article: since I typed character 1234 in a short period of time, what I expect to see in the UI is the result that the background service returns when it receives 1234. I no longer care how the background handles the first three requests, namely character 1, character 12, and character 123.

We can implement anti-shake control for SAP UI5 function calls, mimicking the elevator door closing timeout setting.

The debounce variable below is a function constructor, itself a function, that takes another function fn as an input argument and transforms fn into a new function with shock control via a closure that returns the return statement on line 17.

The buffeting interval is specified by another input argument to the function constructor, delay.

Assuming we specify a buffeting interval of 3000 milliseconds or 3 seconds, if within 3 seconds a new function returned by the debounce function constructor is repeatedly called, line 19 of the above code is executed and clearTimeout is called to reset the counter, the original fn function is not executed. This scenario can be likened to: when a new passenger enters the elevator during the closing time, the elevator timer resets and the elevator door does not close.

At line 20, use setTimeout to restart a counter with a timeout interval of 3 seconds. After 3 seconds, if there are no other tasks in the JavaScript task queue, the original function fn. Line 20 of the code says that the elevator equipment has restarted its three-second timeout timer.

If no new function call is triggered within three seconds of waiting, the original function fn on line 21 is executed after three seconds. This is like the elevator in 3 seconds, always no new passengers enter, then 3 seconds later, the elevator door automatically closed.

The Debounce function constructor is also simple to use.

On line 78, pass the original sendRequest function, along with the 3000 millisecond buffering interval, to the Debounce constructor, returning a debounceVersion function that combines data sending and buffering. On line 85, call debounceVersion instead of sendRequest.

Function of image stabilization function test: I’m in the same minutes 46 seconds, 48 seconds, 50 seconds, 51 seconds four point in time, the input 1, 2, 3, 4 respectively a total of four characters, but in the last 51.996 seconds and after three seconds, just only have one request is sent to the background: that means 3 seconds interval function stabilization effect:

How can SAP UI5 use function throttling to reduce the frequency of function calls

There is a problem in the realization of the above functions, or to illustrate the elevator example.

Imagine an elevator with unlimited space. The closing time is three seconds. If new passengers continuously enter the elevator at intervals of less than 3 seconds, the elevator door never closes — that is, the function never executes.

Function throttling is another way to reduce the frequency of function calls, which differs from function stabilization by ensuring that the function is executed at least once within a specified throttling interval.

One of the simplest implementations of the function throttling constructor:

Each time the function modified by the restrictor fires, it takes a current system timestamp and compares it to the timestamp taken at the previous firing. If the time difference between the two is greater than or equal to the constructor’s input parameter delay (the throttling time interval), the else branch on line 39 triggers the original function fn. Otherwise, the throttling interval has not been reached. Use line 34 setTimeout to put the original function fn back into the JavaScript event queue and delay execution:

Function throttling constructors are used in the same way as function stabilization constructors: ThrottleVersion (sendRequest) is throttleVersion (throttleVersion). ThrottleVersion (sendRequest) is throttleVersion (sendRequest). ThrottleVersion (sendRequest) is throttleVersion (sendRequest).

Function throttling test result: I set throttling interval to 3 seconds, from Chrome console print can be seen, SAP UI5 really is a 3 second interval to background data requests.

In this paper, the implementation codes of two kinds of function anti-shake and function throttling are only considered the most basic situation, and there are still many imperfect places. Interested friends can search on the network. There are a lot of information in this respect, which will not be repeated here.

As Jerry mentioned in his previous share, Angular is a heavy user of the responsive programming development library RxJS, which provides a number of powerful Operators that allow Angular developers to easily implement scenarios with function stabilization and function throttles without having to repeat the wheel.

Re-implement SAP UI5 Demo with Angular with only 44 lines of code:

DebounceTime and throttleTime operators are exported directly from the RXJS/Operators library:

Like SAP UI5 Input control liveChange, Angular FormControl valueChanges gives application developers a place to write business logic in response to user Input: The valueChanges data type of the latter is Observable, which application developers can call through PIPE and pass in various powerful RxJS Operators to trigger their own event response functions containing business logic according to actual requirements.

For example, in line 39 above, the semantics are: When valueChanges occur on an input control bound to jerryFormControl, it is first processed by the shaker. The internal processing logic of debounceTime determines whether the event handler corresponding to valueChanges can be triggered.

The internal implementation of RxJS debounceTime uses setInterval, and the logic is much more complex than Jerry’s Debounce constructor, as can be seen from these call stacks:

Jerry’s Angular Demo function throttling (interval set to 2 seconds) was tested as follows: WITHIN 7 seconds, I typed 1234567890abc at a constant speed and saw three requests sent to the background at 2-second intervals:

Hopefully this article has given you a rudimentary understanding of the concepts of function stabilization and function throttling. Thank you for reading.



Read more

(0) SAP UI5 application developers understand the meaning of UI5 framework code

(1) LAZY loading mechanism of SAP UI5 Module

(2) SAP UI5 control rendering mechanism

(3) HTML native event VS SAP UI5 Semantic event

(4) Metadata implementation of SAP UI5 control metadata

(5) instance data modification and reading logic of SAP UI5 control

(6) Implementation principle of SAP UI5 control data binding

(7) Comparison of implementation principles of three data binding modes of SAP UI5 control: One Way, Two Way and OneTime

(8) The generation logic of SAP UI5 control ID

(9) SAP UI5 controls multiple languages (Internationalization, the Internationalization, i18n) support the implementation of the principle

(10) Button control in XML view

(11) Button control and the DOM element behind it

(12) SAP UI5 OData rumor shredder: Send two OData requests in a very short time, will the first one be automatically cancelled

(13) One of the Checkbox design and implementation series on the page of SAP products

More of Jerry’s original articles can be found in “Wang Zixi” :