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

Solve the problem that await does not work in forEach

1. Introduction A few days ago, I encountered a p...

WeChat applet picker multi-column selector (mode = multiSelector)

Table of contents 1. Effect diagram (multiple col...

How to use module fs file system in Nodejs

Table of contents Overview File Descriptors Synch...

Detailed explanation of Angular data binding and its implementation

Table of contents Preface What is data binding? T...

How to change the mysql password on the Xampp server (with pictures)

Today, I found out while working on PHP that if w...

What is ssh? How to use? What are the misunderstandings?

Table of contents Preface What is ssh What is ssh...

Using react-beautiful-dnd to implement drag and drop between lists

Table of contents Why choose react-beautiful-dnd ...

A brief discussion on Flex layout and scaling calculation

1. Introduction to Flex Layout Flex is the abbrev...

Two ways to start Linux boot service

Table of contents rc.local method chkconfig metho...

Detailed explanation of map overlay in openlayers6

1. Overlay Overview Overlay means covering, as th...

How to quickly copy large files under Linux

Copy data When copying data remotely, we usually ...

Install tomcat and deploy the website under Linux (recommended)

Install jdk: Oracle official download https://www...

How to add custom system services to CentOS7 systemd

systemd: The service systemctl script of CentOS 7...

4 flexible Scss compilation output styles

Many people have been told how to compile from th...

How to use React to implement image recognition app

Let me show you the effect picture first. Persona...