JS function anti chattering and throttling

<div id="content"
    style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;">
</div>
  <script>
    let num = 1;
    const content = document.getElementById('content');
    function count() {
      	content.innerHTML = num++;
    };
    content.onmousemove = count;
 </script>

Effect achieved:

Anti shake

The so-called anti shake means that the function is executed n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time will be recalculated.

Non immediate function:

After the event is triggered, the function will not execute immediately, but after n seconds. If the event is triggered again within n seconds, the function execution time will be recalculated.

Implementation method: using timer, when the function first calls, set a timer. After calling, it is found that the timer that has already existed is emptied before the timer is set, and a new timer is reset. If there is a timer that has not been cleared, the function is triggered to execute when the timer timing ends

// Every time an event is triggered, in any case, clear the timer before starting a new timer
function debounce(func, wait) {
    let timeout;
    return function () {
        const context = this;
        const args = [...arguments];
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(() => {
            func.apply(context, args)
        }, wait);
    }
}

content.onmousemove = debounce(count,1000);

Effect achieved:

Execute function now:

After the event is triggered, the function will execute immediately, and then the effect of executing the function can continue only if the event is not triggered within n seconds.

In order to improve the user experience, the function needs to be executed immediately when it is called for the first time.

Implementation method: add the function of triggering immediate execution for the first time to the original implementation.

function debounce(func,wait) {
    let timeout;
    return function () {
        const context = this;
        const args = [...arguments];
        if (timeout) clearTimeout(timeout);
        const callNow = !timeout;
        timeout = setTimeout(() => {
            timeout = null;
        }, wait)
        if (callNow) func.apply(context, args)
    }
}

content.onmousemove = debounce(count,1000);

Effect achieved:

throttle

Throttling means that events are triggered continuously, but the function is executed only once in n seconds. Throttling dilutes the execution frequency of the function.

Timestamp method:

During the continuous triggering of the event, the function is executed immediately and every ns.

Implementation method: record the time of function call by timestamp, and determine whether the waiting time has been achieved by calculating the time difference between the current call timestamp and the time stamp of the last call. If so, execute the function and update the timestamp of the last call. Otherwise, ignore this call.

function throttle(func, wait) {
    var previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}
content.onmousemove = throttle(count,1000);

Effect achieved:

Timer method:

In the process of continuously triggering the event, the function will not execute immediately, and will execute once every ns. After stopping the triggering event, the function will execute again.

Implementation method: when calling the function, judge whether there is a timer currently. If the timer exists, it will not be executed. After knowing the wait time, the timer executes the function, clears the timer and continues to set the next timer.

function throttle(func, wait) {
    let timeout;
    return function() {
        let context = this;
        let args = arguments;
        if (!timeout) {
            timeout = setTimezhixingout(() => {
                timeout = null;
                func.apply(context, args)
            }, wait)
        }

    }
}
content.onmousemove = throttle(count,1000);

Effect achieved:

difference:

  • The function trigger of the timestamp version is at the beginning of the time period
  • The function trigger of timer version is at the end of the time period.

Comparison between anti chattering and throttling

Similarities:

  • Can be achieved by using setTimeout
  • The purpose is to reduce the callback execution frequency and save computing resources

difference:

  • Anti shake. After a continuous operation, handle the callback, which is realized by clearTimeout and setTimeout. Throttling is performed only once in a period of continuous operation. It is used in events with high frequency to improve performance
  • Anti shake focuses on events triggered continuously for a certain period of time, which are only executed once at the last time. Throttling focuses on executing only once over a period of time

Application scenario:

Function anti shake:

For continuous events, only one callback needs to be triggered:

  • Search box search input. The user only needs to input it for the last time before sending the request
  • Mobile phone number and email verification input detection
  • Window size Resize. Just calculate the window size after the window adjustment is completed. Prevent duplicate rendering

Function throttling:

Scenarios in which callback is performed at intervals include:

  • Scroll load, load more or scroll to the bottom
  • Google search box, search association function
  • Click Submit frequently, and the form will be submitted repeatedly

Reference article:

Function anti chattering and throttling

JavaScript anti shake and throttling

Keywords: Javascript

Added by reflash on Sun, 21 Nov 2021 22:58:44 +0200