Throttling and anti-shaking

This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Background: When we frequently request resources, interfaces, etc., it will cause frequent Dom operations, heavy interface pressure, etc., and performance degradation. For example, SOMETIMES I would slam enter every time I searched, and when the network was not good, I would keep hitting the next page button, maybe the network was bad or the server performance was low.

To avoid triggering the same event or request too often, throttling and anti-shaking are used.

What? What is this 😕? When I first heard these two names, I thought they meant to save traffic and prevent hand shaking. Puzzled, quickly to learn.

Concept:

Simply put: Throttling and stabilization are two solutions to prevent events from firing multiple times in a short period of time. Both have been used to reduce the number of requests to reduce stress and improve performance.

The difference between

Throttling: Only one request is made for a certain period of time.

The bus, each person is a click request, every ten minutes to run, send requests

Buffeting: 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.

Let’s say I keep clicking on a button for a period of time and send a request based on the last click.

Throttling implementation

🤖 : Using a timestamp (which occurs at the beginning of a period of time) is computing

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

Disadvantages: The first direct trigger and the last one cannot trigger for a period of time

To give a scenario, when we’re searching for data, we make a request, and we don’t do any processing. It must be too frequent

Throttling function

Code:

<body>
    <div>
        <span>The throttling process</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 execute, and delay is the delay time
        var last = 0;  // The last time it ended
        return function () {
            var cur = Date.now()
            console.log(cur-last)
            if (cur - last > delay) {
                fn.apply(this.arguments)  // Execute the function
                last = cur // Update the last time}}}</script>

Copy the code

Effect:

If you realize

🤖 Solution: Timer (occurs when the timer ends). Disadvantages: The first time does not trigger the last delay trigger

Is to set a timer, if always click to clear the timer, the last time to open the timer

Image stabilization function

Code:

<body>
    <div>
        <span>If you deal with</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 execute, and delay is the delay time
        var time = null;  / / timer
        return function () {
            clearTimeout(time);  // Clear the timer
            let context = this;  // Get the current button context. If not specified, the arrow function finds the window all the way out
            let args = arguments;
            time = setTimeout(() = >{ fn.apply(context, args); }, delay); }}</script>

Copy the code

Effect:

Anti-shake upgraded version

First trigger and last delay trigger

Code:

    function throttle(fn, delay) {  // fn is the function to execute, and delay is the delay time
        let time = null
        let flag=true  // Indicates whether it is the first time
        return function () {
            clearTimeout(time)
            if (flag) { 
                fn.apply(this.arguments)
                flag=false
            }
            time = setTimeout(() = > {  // Trigger the timer
                fn.apply(this.arguments)
                flag=true
            }, delay)
        }
    }
Copy the code

Effect:

Write in the last

💌 The real problem is not growing up, but forgetting 💌

A romantic universe, but also cherish the world’s daily code farmers