Correct use of Vue function anti-shake and throttling

Correct use of Vue function anti-shake and throttling

Preface

1. Debounce: After a high-frequency event is triggered, the function will only be executed once within n seconds. If the high-frequency event is triggered again within n seconds, the time will be recalculated.

For example: Just like when searching on Baidu, there will be associated words popping up after each input. This method of controlling the associated words cannot be triggered as soon as the content of the input box changes. It must be triggered after a period of time after you finish inputting.

Throttling: High-frequency events are triggered, but they are only executed once within n seconds, so throttling will dilute the execution frequency of the function

For example: a function is scheduled to be executed only when it is greater than or equal to the execution cycle, and it will not be executed if called during the cycle. It’s like when you’re trying to buy a limited-edition hot-selling item on Taobao, you keep clicking on the refresh button to buy, but there comes a time when no clicks work. This is where throttling comes in, because you’re afraid that clicking too quickly will cause a bug in the system.

2. Difference: Anti-shake is to turn multiple executions into the last execution, and throttling is to turn multiple executions into executions at intervals.

Function anti-shake and throttling are always interview topics. Everyone may be familiar with the writing of function anti-shake and throttling, but there is a small episode when using function anti-shake or throttling in Vue.

Correct usage posture in Vue

I believe that many people will directly define the function and then use debounce in the function . This is a wrong way to use it.

Why? This is related to the event binding principle of Vue, which will not be introduced in detail here. If used directly inside the function body, the final result is that an anonymous immediately executed function is executed, which is wrong. Detailed reference

principle

Function deshaking

Function anti-shake refers to the time after which the function is executed. We can understand it as a life scenario (taking an elevator). After clicking the elevator door opening button , the elevator will open the door and then wait for a while to close the door. However, if someone clicks the door opening button again during the waiting period, the elevator will continue to wait for the door closing time . The elevator will not start working until the door closing time is over and no one clicks the door opening button.

Code Writing

First non-immediate execution

export function debounce(f, t){
    let timer;
    return (...arg) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            f( ...arg)
        }, t)
    }
}

First immediate execution

For some scenarios, I don't need to wait for the first time and need to execute immediately, for example: open the console to get the window view size (here we need to keep changing the window size, wait until it stops and get the window view size again).

export function debounceFirstExe(f, t){
    let timer, flag = true;
    return (...args) => {
        if (flag){
            f(...args);
            flag = false;
        }else {
            clearTimeout(timer);
            timer = setTimeout(() => {
                f(...args);
                flag = true;
            }, t)
        }
    }
}

Merged version

export function debounce(f, t, im = false){
    let timer, flag = true;
    return (...args) => {
        // Need to execute immediately if (im){
           if (flag){
               f(...args);
               flag = false;
           }else {
               clearTimeout(timer);
               timer = setTimeout(() => {
                   f(...args);
                   flag = true
               }, t)
           }
       }else {
           // Non-immediate execution clearTimeout(timer);
           timer = setTimeout(() => {
               f(...args)
           }, t)
       }
    }
}

Where can we use function anti-shake at the code level?

When sending network hydrogen such as likes, input box verification, cancel likes, create orders, etc., if we click the button continuously, multiple requests may be sent. This is not allowed for the backend. A statistics event is triggered every time the mouse is resized/scrolled.

Function throttling

The principle of function throttling is similar to that of function anti-shake. Function throttling means that it will only be executed once within a certain period of time.

First non-immediate execution

export function throttle(f,t){
    let timer = true;
    return (...arg)=>{
        if(!timer){
            return;
        }
        timer=false;
        setTimeout(()=>{
            f(...arg);
            timer=true;
        },t)

    }
}

In the effect, we clicked many times, but it was only executed 4 times because I specified the execution time to be 1000ms. This also reduces the number of execution times.

First immediate execution version

export function throttleFirstExt(f, t) {
    let flag = true;
    return (...args) => {
        if (flag) {
            f(...args);
            flag = false;
            setTimeout(() => {
                flag = true
            }, t)
        }
    }
}

Here we see that the first click is executed immediately.

Merged version

export function throttle(f, t, im = false){
    let flag = true;
    return (...args)=>{
        if(flag){
            flag = false
            im && f(...args)
            setTimeout(() => {
                !im && f(...args)
                flag = true
            },t)
        }
    }
}

Application scenarios:

  • Implementation of dragging function of DOM elements (mousemove)
  • Search for association (keyup)
  • Calculate the distance the mouse moves (mousemove)
  • Canvas simulates the drawing board function (mousemove)
  • Mousedown/keydown events in shooting games (only one bullet can be fired per unit time)
  • Listen to scroll events to determine whether the page has reached the bottom and automatically load more: After adding debounce to scroll, it will only determine whether it has reached the bottom of the page after the user stops scrolling; if it is throttle, it will be determined once every period of time as long as the page is scrolled.

Summarize

This is the end of this article about the correct use of Vue function anti-shake and throttling. For more relevant Vue function anti-shake and throttling content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Understanding and application of function anti-shake throttling in Vue
  • How to use anti-shake and throttling in Vue
  • Using anti-shake and throttling in Vue, and the problem pointed to by this

<<:  How to quickly build ELK based on Docker

>>:  Solution to the problem that MySql always pops up the mySqlInstallerConsole window

Recommend

How to set the memory size of Docker tomcat

When installing Tomcat in Docker, Tomcat may over...

Examples of using the Li tag in HTML

I hope to align the title on the left and the dat...

A time-consuming troubleshooting process record of a docker error

Table of contents origin Environmental Informatio...

MySQL stored procedure in, out and inout parameter examples and summary

Stored Procedures 1. Create a stored procedure an...

Detailed explanation of the calculation method of flex-grow and flex-shrink in flex layout

Flex(彈性布局) in CSS can flexibly control the layout...

Linux uses if to determine whether a directory exists.

How to use if in Linux to determine whether a dir...

HTML5+CSS3 coding standards

The Golden Rule No matter how many people are wor...

Vue-Router installation process and principle detailed

Table of contents 1. Front-end routing implementa...

React's context and props explained

Table of contents 1. context 1. Usage scenarios 2...

Installation tutorial of mysql 8.0.11 compressed version under win10

This article shares the installation tutorial of ...

Detailed explanation of dynamic Christmas tree through JavaScript

Table of contents 1. Animated Christmas Tree Made...

8 commands to effectively manage processes in Linux

Preface The role of process management: Determine...

js implements axios limit request queue

Table of contents The background is: What will ha...

Database SQL statement optimization

Why optimize: With the launch of the actual proje...