preface

High frequency triggering events, onscroll/onresize is a high frequency triggering event, and events such as crazy clicking and frequent triggering events are always easy to trigger, causing great performance problems.

What is anti-shake and throttling

Function debounce: The function is executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time is recalculated. — Every time you click, immediately clear the timer after clicking

Function throttling: A high-frequency event fires but only executes once in n seconds, so throttling dilutes the function’s execution frequency. — Click once and the job is done. Click until it is done is useless

Take a chestnut

Function image stabilization

// The height of the body can be set to trigger the onsroll event
   var t;
        window.onscroll = function() {
            clearTimeout(t);
            t = setTimeout(function() {
                console.log(888);
            }, 300)}Copy the code

The result is as follows: if the function is not shaken, then the scroll bar slide event is triggered and 888 prints a lot of prints. After the function is shaken, you can see how little is printed

Function of the throttle

A common example is that the captcha can be retrieved after 60 seconds, during which the captcha button cannot be clicked. So make sure you use the disable attribute in the form, which is Boolean (note: click events are triggered frequently and click events are superimposed)

 <button id="btn"</button><script>
        // function throttling, event processing completed before proceeding to the next
        var oBtn = document.getElementById('btn')
        
         // Click the event
        oBtn.onclick = function() {
            / / disabled for the disabled
            oBtn.disabled = true;
            oBtn.style = "background:#666;"
            var count = 10;
            oBtn.innerHTML = count + 's can be retrieved after '

            / / timer
            var t = setInterval(function() {
                count--;
                oBtn.innerHTML = count + 's can be retrieved after '
                if (count <= 0) {
                    // Clear the timer when the conditions are met
                    clearInterval(t);
                    oBtn.innerHTML = 'Get captcha'
                    oBtn.disabled = false;
                    oBtn.style = "background:#E5E5E5;"}},1000)}</script>
Copy the code

The result is as follows: After the button is disabled, the click event can be triggered again only after the timer ends. In this way, the event triggering frequency is reduced and the frequent triggering events can be resolved.