A brief discussion on JavaScript throttling and anti-shake

A brief discussion on JavaScript throttling and anti-shake

Throttling and anti-shake

Background : When we frequently request resources, interfaces, and other things, it will cause frequent Dom operations, high interface pressure, and so on, resulting in performance degradation. For example, sometimes I would suddenly hit the enter key every time I searched, and when the network connection was not very good, I would keep clicking the next page button. It might be because of the bad network or the low server performance.

In order to avoid frequently triggering the same event or request, throttling and anti-shake are used at this time.

what? What is this? When I first heard these two names, I thought they meant saving data traffic and preventing hand shaking. I was puzzled and started to learn immediately.

concept:

Simply put: throttling and anti-shake are two solutions to prevent events from being triggered multiple times in a short period of time. They all use the method of reducing the number of requests to reduce pressure and improve performance.

the difference

Throttling : Only one request will be made within a certain period of time.

It can be understood as: on a bus, each person is a click request, a bus runs every ten minutes, and a request is sent

Anti-shake : The function can be executed n seconds after the event is triggered. If the event is triggered within n seconds, the execution time will be recalculated.

For example, if I keep clicking a button for a period of time, a request will be sent based on the last click.

Throttling Implementation

Solution:

Using a timestamp (occurring at the beginning of a period of time) is to calculate

The current click time - the last time the function was executed > the timestamp I set, the function is executed once

Disadvantages: The first trigger is triggered directly, and the last trigger cannot be triggered within a period of time

Let's take a scenario where we search for data and initiate a request without doing any processing. The request must be too frequent.

insert image description here

Throttling function

Code:

<body>
    <div>
        <span>Throttling</span><input id="input" type="text">
        <button id="btn">Request</button>
    </div>
</body>
<script>
    var btn = document.getElementById("btn")
    btn.addEventListener("click", throttle(output, 1000)) //Add click event listener function output(e) {
        console.log(this, e)
        console.log(document.getElementById("input").value) //Simulate a request}
//Throttling function function throttle(fn, delay) { // fn is the function to be executed, delay is the delay time var last = 0; //The last end time return function () {
            var cur = Date.now()
            console.log(cur-last)
            if (cur - last > delay) {
                fn.apply(this, arguments) //Execute function last = cur //Update the last time}
        }
    }
</script>

Effect:

insert image description here

Anti-shake implementation

Solution:

Timer (occurs when the timer ends). Disadvantages: The first time does not trigger, the last time is delayed

It is to set a timer. If you keep clicking, the timer will be cleared and the last time the timer is turned on

Anti-shake function

Code:

<body>
    <div>
        <span>Anti-shake processing</span><input id="input" type="text">
        <button id="btn">Request</button>
    </div>
</body>
<script>
    var btn = document.getElementById("btn")
    btn.addEventListener("click", debounce(output, 1000)) //Add click event listener function output(e) {
        console.log(this, e)
        console.log(document.getElementById("input").value) //Simulate a request}
    function debounce(fn, delay) { // fn is the function to be executed, delay is the delay time var time = null; //timer return function () {
            clearTimeout(time); //Clear timer let context = this; //Get the current button context If not specified, the arrow function will always look out to find the window
            let args = arguments;
            time = setTimeout(() => {
                fn.apply(context, args);
            }, delay);
        }
    }
</script>

Effect:

insert image description here

Anti-shake upgraded version

First trigger and last delayed trigger

Code:

    function throttle(fn, delay) { // fn is the function to be executed, delay is the delay time let time = null
        let flag=true //Is it the first time to trigger return function () {
            clearTimeout(time)
            if (flag) { 
                fn.apply(this, arguments)
                flag=false
            }
            time = setTimeout(() => { //Trigger timer fn.apply(this, arguments)
                flag=true
            }, delay)
        }
    }

Effect:

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

Throttling and anti-shake

Background : When we frequently request resources, interfaces, and other things, it will cause frequent Dom operations, high interface pressure, and so on, resulting in performance degradation. For example, sometimes I would suddenly hit the enter key every time I searched, and when the network connection was not very good, I would keep clicking the next page button. It might be because of the bad network or the low server performance.

In order to avoid frequently triggering the same event or request, throttling and anti-shake are used at this time.

what? What is this? When I first heard these two names, I thought they meant saving data traffic and preventing hand shaking. I was puzzled and started to learn immediately.

concept:

Simply put: throttling and anti-shake are two solutions to prevent events from being triggered multiple times in a short period of time. They all use the method of reducing the number of requests to reduce pressure and improve performance.

the difference

Throttling : Only one request will be made within a certain period of time.

It can be understood as: on a bus, each person is a click request, a bus runs every ten minutes, and a request is sent

Anti-shake : The function can be executed n seconds after the event is triggered. If the event is triggered within n seconds, the execution time will be recalculated.

For example, if I keep clicking a button for a period of time, a request will be sent based on the last click.

Throttling Implementation

Solution:

Using a timestamp (occurring at the beginning of a period of time) is to calculate

The current click time - the last time the function was executed > the timestamp I set, the function is executed once

Disadvantages: The first trigger is triggered directly, and the last trigger cannot be triggered within a period of time

Let's take a scenario where we search for data and initiate a request without doing any processing. The request must be too frequent.

insert image description here

Throttling function

Code:

<body>
    <div>
        <span>Throttling</span><input id="input" type="text">
        <button id="btn">Request</button>
    </div>
</body>
<script>
    var btn = document.getElementById("btn")
    btn.addEventListener("click", throttle(output, 1000)) //Add click event listener function output(e) {
        console.log(this, e)
        console.log(document.getElementById("input").value) //Simulate a request}
//Throttling function function throttle(fn, delay) { // fn is the function to be executed, delay is the delay time var last = 0; //The last end time return function () {
            var cur = Date.now()
            console.log(cur-last)
            if (cur - last > delay) {
                fn.apply(this, arguments) //Execute function last = cur //Update the last time}
        }
    }
</script>

Effect:

insert image description here

Anti-shake implementation

Solution:

Timer (occurs when the timer ends). Disadvantages: The first time does not trigger, the last time is delayed

It is to set a timer. If you keep clicking, the timer will be cleared and the last time the timer is turned on

Anti-shake function

Code:

<body>
    <div>
        <span>Anti-shake processing</span><input id="input" type="text">
        <button id="btn">Request</button>
    </div>
</body>
<script>
    var btn = document.getElementById("btn")
    btn.addEventListener("click", debounce(output, 1000)) //Add click event listener function output(e) {
        console.log(this, e)
        console.log(document.getElementById("input").value) //Simulate a request}
    function debounce(fn, delay) { // fn is the function to be executed, delay is the delay time var time = null; //timer return function () {
            clearTimeout(time); //Clear timer let context = this; //Get the current button context If not specified, the arrow function will always look out to find the window
            let args = arguments;
            time = setTimeout(() => {
                fn.apply(context, args);
            }, delay);
        }
    }
</script>

Effect:

insert image description here

Anti-shake upgraded version

First trigger and last delayed trigger

Code:

    function throttle(fn, delay) { // fn is the function to be executed, delay is the delay time let time = null
        let flag=true //Is it the first time to trigger return function () {
            clearTimeout(time)
            if (flag) { 
                fn.apply(this, arguments)
                flag=false
            }
            time = setTimeout(() => { //Trigger timer fn.apply(this, arguments)
                flag=true
            }, delay)
        }
    }

Effect:

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Implementation and precautions of JavaScript anti-shake and throttling
  • Let’s learn about JavaScript anti-shake and throttling
  • Detailed explanation of anti-shake and throttling of functions in JavaScript
  • A commonplace discussion on Javascript anti-shake and throttling
  • Do you know about JavaScript anti-shake and throttling?
  • Analysis of JavaScript's anti-shake throttling function
  • What is JavaScript anti-shake and throttling
  • JavaScript in-depth understanding of throttling and anti-shake

<<:  Gogs+Jenkins+Docker automated deployment of .NetCore steps

>>:  Web front-end development experience summary

Recommend

Detailed steps to install and uninstall Apache (httpd) service on centos 7

uninstall First, confirm whether it has been inst...

Forty-nine JavaScript tips and tricks

Table of contents 1. Operation of js integer 2. R...

Detailed introduction to linux host name configuration

Table of contents 1. Configure Linux hostname Con...

Basic usage of wget command under Linux

Table of contents Preface 1. Download a single fi...

Summary of MySQL character sets

Table of contents Character Set Comparison Rules ...

Similar to HTML tags: strong and em, q, cite, blockquote

There are some tags in XHTML that have similar fu...

React Routing Link Configuration Details

1. Link's to attribute (1) Place the routing ...

mysql obtains statistical data within a specified time period

mysql obtains statistical data within a specified...

Getting Started Guide to MySQL Sharding

Preface Relational databases are more likely to b...

In-depth interpretation of /etc/fstab file in Linux system

Preface [root@localhost ~]# cat /etc/fstab # # /e...

Detailed explanation of process management in Linux system

Table of contents 1. The concept of process and t...

Detailed explanation of the usage of grep command in Linux

1. Official Introduction grep is a commonly used ...