Because of it, I almost deleted the library and ran away: js anti shake and throttling

preface

Front end stepping on Thunder: repeated submission in a short time leads to repeated data.

For the front-end boss, the application of anti shake and throttling technology is the basic operation. For "part-time" front-end developers, these are pits that need to lie flat.

Let's play js anti shake and throttling today, and solve the problems encountered in development.

PS: I use the anti shake method to avoid repeatedly submitting questions.

Anti shake concept

Anti shake is also called function anti shake (debounce): it means that the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within n seconds after the event is triggered, the function execution delay will be recalculated.

In front-end development, common events such as onresize, scroll, MouseMove, mousehover, etc. will be triggered many times in a short time (frequently). If there is no limit, it may be executed hundreds of times a second,

If other functions are executed inside these functions, especially those that operate DOM (browser operation of DOM is very performance-consuming), it will not only waste computer resources,

It will also reduce the running speed of the program, and even cause the browser to jam and crash.

In addition, calling ajax repeatedly in a short time will not only cause confusion in data relations, but also cause network congestion and increase server pressure.

Implementation of anti shake code

The key to anti shake is to need a setTimeout to assist the implementation and delay the execution of the code.

If the method is triggered multiple times, clear the last recorded delayed execution code with clearTimeout and restart timing.

If the event is not triggered again during the timing, the object code will be executed after the delay time is timed.

Note: when you click continuously for more than the time you set, and only the first click is valid, this is not a bug, this is a conceptual problem. Pay attention to the bold part below,

Anti shake is also called function anti shake (debounce): it means that the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within n seconds after the event is triggered, the function execution delay will be recalculated.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js Anti shake and throttling</title>
</head>
<body>
    <!--Button-->
    <button id="btn">Click Submit</button>

    <script type="text/javascript">

        var num = 1;
        const seckill = () => {
            console.log('I'm anti shake. You clicked the button' + num++)
        }

        // Anti shake function
        const debounce = (fun, wait) => {
            let timeout;
            return function () {
                if (timeout) {
                    clearTimeout(timeout);
                }
                //When the task is executed for the first time, the timeout is null. At this time, callNow is true and needs to be executed immediately
                let callNow = !timeout;
                timeout = setTimeout(() => {
                    timeout = null;
                }, wait);
                if (callNow) {
                    fun.apply(this);
                }
            }
        };
        //Click the submit button
        let btn = document.getElementById('btn');
        //Call method (only one operation is allowed in 1s)
        btn.addEventListener('click', debounce(seckill, 1000));  

    </script>

</body>
</html>

Concept of throttling

Throttling is also called function throttling: when an event is triggered continuously, it is ensured that the event handling function is called only once within a certain period of time.

Throttle code implementation

  • The mouse continuously triggers an event (such as clicking), which is triggered only once in a unit time;
  • In the scenario of unlimited page loading, users need to send ajax requests every once in a while when scrolling the page, instead of requesting data when users stop scrolling the page;
  • Monitor scrolling events, such as whether to slide to the bottom and automatically load more, and use the throttle to judge;
  • Throttling and anti chattering are similar, but the difference is that they are "immediate execution version" and "non immediate execution version"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js Anti shake and throttling</title>
</head>
<body>
    <!--Button-->
    <button id="btn">Click Submit</button>

    <script type="text/javascript">

        var num = 1;
        const seckill = () => {
            console.log('Click the button' + num++)
        }
        function throttle(callback, delay) {
            var timer, begin = new Date();
            return function () {
                //Record the time when the event was triggered
                var current = new Date();
                //Clear last timer task
                clearTimeout(timer);
                //Determine whether the delay time has elapsed since the last trigger
                if (current - begin >= delay) {
                    callback();
                    begin = current;
                } else {
                    timer = setTimeout(() => {
                        callback();
                    }, delay);
                }
            }
        }
        //Click the submit button
        let btn = document.getElementById('btn');
        //Call method (only one operation is allowed in 1s)
        btn.addEventListener('click', throttle(seckill, 1000));

    </script>

</body>
</html>

Difference between anti shake and throttling

Function anti shake: it is only executed once in n seconds. If an event is triggered within n seconds after the event is triggered, the function execution delay will be recalculated.

Function throttling: it is executed at an interval. No matter how frequently events are triggered, it will ensure that the real event processing function will be executed within the specified time.

Principle:

Anti shake is to maintain a timer. It is required to trigger the function after the delay time. However, if it is triggered again within the delay time, the current timer will be cleared and the timeout call will be reset, that is, re timing. In this way, only the last operation can be triggered.
 
Throttling is to trigger the function by judging whether a certain time has been reached. If the specified time has not been reached, the timer will be used to delay, and the timer will be reset for the next event.

summary

The implementation of function anti shake and throttling is very simple. It can friendly solve many problems encountered in the front-end development process, improve performance and optimize user experience.

In the actual development, the choice of anti shake function or throttling function requires developers to apply it according to different application scenarios.

Welcome to subscribe to WeChat public official account.
Author: Xiong Ze - pain and joy in learning
Official account: Bear's saying
Source 1: https://www.cnblogs.com/xiongze520/p/15011323.html
Source 2: https://blog.csdn.net/qq_35267585/article/details/118730059
It is not easy to create. If anyone, group or organization reprints or excerpts all or part of it, please indicate the author and the link to the original text in the obvious position of the article.

Keywords: Javascript Front-end

Added by ld0121 on Mon, 17 Jan 2022 06:08:05 +0200