The introduction

The Chinese New Year is just over a month away. Warm reminder: small friends should grab tickets. 🏮

When it comes to Chinese New Year, we have to mention the Spring Festival travel rush. During the Spring Festival travel rush, we can experience the improvement of order and efficiency brought by the idea of reducing expenditure and preventing vibration.

Scenario 1: Security check

The subway goes through security, and security inspectors will control the flow of people at the entrance. When the flow of people is too much, it will timely block the flow of people behind, play the role of throttling, avoid overcrowding and block security check, and further improve the efficiency of inspection.

Scene 2: A crowded minibus.

Minibus I don’t know if you have experienced. If a succession of passengers boarded the bus, the conductor is generally not easy to leave. He probably thought, “Wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait. At this point, has boarded the passengers heart bitter ah… Of course, in terms of transportation efficiency, the application of this typical anti-shake idea greatly improves transportation efficiency and avoids the waste of transportation resources.

The principle of analysis

The concept of function throttling and anti – shake is an old one. It’s been written a lot. If you don’t know much about it, that’s ok. This article hopes to give you a more comfortable understanding experience. 🙂

Assuming that

The event handler is A;

The throttling (or anti-shaking) function is B;

Then, when the final event fires, it actually executes the internal function (closure) returned by **B(A)**.

Throttling: For continuous event firing, execute event handler A every time A fixed interval is reached.

Debounce function: Starts the timer after the event trigger stops. After A fixed period of time when no event is triggered, the event handler A is executed.

Later, we will combine concrete examples to strengthen our understanding. 😬

The important role

Before we get into the specifics, I want you to ask yourself a few questions, right?

  • Why is thereThe throttleandImage stabilizationWhat kind of problems are they trying to solve?
  • In order to improve the quality of the code, do you want to use it in daily development?

After reading this article, I hope you can get the answer.

As a front-end developer with “zero distance” from users, user experience should be sISI’s priority. Throttling and anti – shake, is an important means to “please” consumers.

① Optimize user experience (timely feedback, avoid UI rendering block, browser lag);

② Improve page performance (avoid page rendering lag, reduce server pressure, prevent malicious trigger);

In daily business development, continuous event processing in the page needs to be optimized by using function throttling and anti-shaking. For example, scroll, resize, input, button click, mousemove, etc. Next, let’s take a look at the implementation and application scenarios.

Application scenarios

The throttle

implementation

@param {Function} fn * @param {Number} delay */
function throttle(fn, delay) {
    var last = 0;
    return function () {
        var now = Date.now();
        if (now - last >= delay) {
            fn.apply(this.arguments); last = now; }}}Copy the code

application

Suppose a business scenario of snatching coupons: users click on coupons continuously, and each time they click on a coupon, they will get one coupon, up to 10 coupons, and a total of 1000 coupons (limited). Just after The Double 11, Ali e-commerce cash flow of more than 200 billion, presumably consumers have grabbed enough coupons. In order to grab more coupons, the user’s normal action should be to keep clicking manually. Instead of doing something unconventional, you might write a for loop and get those 10 coupons easily.

For cycle coupon grab, as shown below:

The graph above shows that the logic of snatching coupons was executed 1000 times. Isn’t that violent? If each user does not receive the maximum limit of 10 times, 1000 coupons, instantly will be malicious snatch. Regular users of the entire network, no matter how fast their hands, can beat a for loop. 😢…

Of course,

Rigorous snatching coupons response logic, will not let such things happen. Check out throttling prevention.

// Coupon click, event handler function
function snatchCouponFn() {
	console.log('Congratulations, you've got your coupon.');
}

// Wrap the coupon event handler with the throttling function
$coupon.onclick = throttle(snatchCouponFn, 2000)

Copy the code

Let’s see what it looks like:

In the end, only one coupon grab logic was executed. ✌ ️

In the example above, function throttling not only improves page performance, but also ensures the security of business applications.

Experience is limited, more aspects of the application, not an example. Feel free to leave your experience in the comments section to help more people put the idea of saving money into practice. 🤝

Image stabilization

implementation

@param {Function} fn * @param {Number} delay */
function debounce(fn, delay) {
    var timer;
    return function() {
        console.log('Event trigger');
      	var self = this,
            argumentsBySelf = arguments;
      	clearTimeout(timer);
      	timer = setTimeout(function() { fn.apply(self, argumentsBySelf); }, delay); }}Copy the code

application

Common scenario: When filling in a form, check whether the form value is valid.

Take a look at how we added anti-shake:

/ / pseudo code
function onInputFn() {
    $error.innerHTML = 'Nickname repeated, please use another nickname';
    console.log('Event Response');
}
              
$name.oninput = debounce(onInputFn, 2000);
Copy the code

According to Debounce, internal functions are fired consecutively when the form input is consecutively entered. The operation performed is to clear the last timer clearTimeout(timer) and reset a timer so that the last timer is never executed and fn is not executed to. However, when the user stops typing into the form and reaches the delay set when debounce is called, the last timer is executed and fn is finally executed to complete the form value verification operation.

Of course, we also use onblur (triggered when form items lose focus) to perform form value validation. But this is not as good as the onInput +debounce solution that gives users timely feedback and experience.

Requirements such as checking whether a nickname is repeated usually require a call to the back-end interface. Using Debounce to wrap the verification function greatly reduces the number of calls to the back-end interface compared to using onInput alone.

insufficient

From the examples of Throrrle and Debounce above, you can see that they have their own flaws:

  • Functions that are throttled will probably no longer give feedback to the user as soon as the user stops firing;

  • The Debounce handled function also gives no feedback to the user when the event is first triggered.

But in many cases, this can lead to a poor or even wrong user experience. So, can we give the user the necessary feedback (event response) at the beginning of the trigger, at the end of the trigger, or during the long trigger? The answer is yes. Let’s look at the implementation.

@param {Function} fn * @param {Number} delay */
function enhancedDebounce(fn, delay) {
    var timer,
        last = 0;

    return function() {
        var self = this,
            argumentsBySelf = arguments,
            now = Date.now();

        if(now - last < delay) {
            clearTimeout(timer);
            timer = setTimout(function() {
            	fn.apply(self, argumentsBySelf);
            }, delay)
        } else {
            fn.apply(this.arguments); last = now; }}}Copy the code

application

… The author makes a follow-up supplement. Feel free to share your app stories in the comments section.

summary

They say the devil is in the details. This article is about the small details of performance optimization in daily development, and I hope you can use them in your own code. Little things make a big difference.

If there are any mistakes or deficiencies in this article, please comment on them. Help the author improve. If it helps, thank you for leaving a like!

This article is published on the author’s public account. If you want to get more high-quality articles in the first time, please pay attention to the public account “Mannong Coffee”.

Bye!