Function anti chattering and function throttling

Use throttling anti chattering function (Performance Optimization)

So how to use it in vue:

In public methods (such as untils.js), add function anti shake and throttling methods

// Anti shake
export function _debounce(fn, delay) {
    var delay = delay || 200;
    var timer;
    return function () {
        var th = this;
        var args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
        }, delay);
    };
}
// throttle
export function _throttle(fn, interval) {
    var last;
    var timer;
    var interval = interval || 200;
    return function () {
        var th = this;
        var args = arguments;
        var now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                fn.apply(th, args);
            }, interval);
        } else {
            last = now;
            fn.apply(th, args);
        }
    }
}

In the component reference that needs to be used

import { _debounce } from "@/utils/public";

Use in methods

  methods: {
    // Change field number
    changefield: _debounce(function(_type, index, item) {
        // do something ...
    }, 200)
  }
Function debounce application:

The callback is executed n seconds after the event is triggered. If it is triggered again within this n seconds, the timing will be restarted.

<body>
      <input type="text" id='unDebounce'>
</body>
</html>

<script>

    //Simulate an ajax request
    function ajax(content){ 
        console.log('ajax request ' + content) 
        };
    letinputa = document.getElementById('unDebounce');
        function fn(e){ ajax(e.target.value) }
    //The anti shake function handles events triggered many times and only executes the last time
    inputa.addEventListener('input', fn)
</script>

Take a look at the running results:

As you can see, we only need to enter one character to trigger this ajax request. Not only is it a waste of resources, but also in practical applications, users will only request after outputting complete characters. Let's optimize:

      <input type="text" id='unDebounce'>
</body>
</html>

<script>
    //Anti shake function
    function _debounce(fn, delay) {
    var delay = delay || 200;
    var timer;
    return function () {
        var th = this;
        var args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
        }, delay);
    };
}

    //Simulate an ajax request
    function ajax(content){ 
        console.log('ajax request ' + content) 
        };
    let inputa = document.getElementById('unDebounce');
    function fn(e){ ajax(e.target.value) }
    //The anti shake function handles events triggered many times and only executes the last time
    inputa.addEventListener('input', _debounce(fn,1000))
</script>

After we add anti shake, when you input frequently, you will not send a request. Only when you do not input within the specified interval will the function be executed. If you stop entering but enter again within the specified interval, the timing will be triggered again.

I personally understand that function anti shake is that the mage should read the note when sending skills. If the skill is not finished, he will read the note again according to the skill.

Function throttle

It is specified that the function can only be triggered once in a unit time. If the function is triggered multiple times in this unit time, only one will take effect.

<body>
      <input type="text" id='unDebounce'>
</body>
</html>

<script>
//Throttling function
function _throttle(fn, interval) {
    var last;
    var timer;
    var interval = interval || 200;
    return function () {
        var th = this;
        var args = arguments;
        var now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                fn.apply(th, args);
            }, interval);
        } else {
            last = now;
            fn.apply(th, args);
        }
    }
}
    //Simulate an ajax request
    function ajax(content){ 
        console.log('ajax request ' + content) 
        };
    let inputa = document.getElementById('unDebounce');
    function fn(e){ ajax(e.target.value) }
    //Anti shake throttling, no matter how many blocks you input, it is executed every 1 second
    inputa.addEventListener('input', _throttle(fn,1000))
</script>


No matter how small the execution interval we set, it is always executed only once in 1s.

Personal understanding: function throttling is the fire speed of fps game. Even if you keep shooting with the mouse, you will only shoot bullets within the specified fire speed.

summary

Both function anti shake and function throttling prevent frequent triggering at a certain time, but the principles between the two brothers are different.
Function anti shake is executed only once in a certain period of time, while function throttling is executed at intervals.

Combined with application scenarios

1.debounce

  • search searches Lenovo. When users constantly input values, they use anti shake to save request resources.
  • When window triggers resize, constantly adjusting the browser window size will continuously trigger this event. Use anti shake to trigger it only once

2.throttle

  • Click the mouse repeatedly to trigger MouseDown (only triggered once per unit time)
  • For drag events, onmousemove will be triggered every time 1px is dragged (it can be optimized with throttle and triggered once per second)
  • Monitor scrolling events, such as whether to slide to the bottom and automatically load more. Use throttle to judge

Keywords: Javascript Vue

Added by Tensing on Sat, 29 Jan 2022 00:26:03 +0200