Throttling & anti – shake are used for high frequency trigger optimization mode

  • Function stabilization: Execute the callback n seconds after the event is triggered, and if it is triggered again within n seconds, re-time (several functions merged into one)
  • Function throttling: specifies that a function can be fired only once per unit of time. If the function fires multiple times in this unit of time, only one function will be executed (once after a certain interval is reached).

Both function throttling and debounce are intended to limit the frequency at which functions are executed to optimize for delays, false death, or stuttering if the response time is too high

Image stabilization

When an event is continuously triggered and no event is triggered again within a certain period of time, the event handler will execute once. If the event is triggered again before the specified time, the delay will start again. As shown in the following figure, handle is not executed when the Scroll event is continuously triggered. The Scroll event will be delayed when no scroll event is triggered within 1000 milliseconds.

function debounce(fn, wait) {
    var timeout = null;
    return function() {
        if(timeout ! == null) clearTimeout(timeout); timeout =setTimeout(fn, wait); }} // handle functionsfunction handle() { console.log(Math.random()); } // The scroll event window.adDeventListener ('scroll', debounce(handle, 1000));
Copy the code

When the Scroll event is continuously triggered, the event handler handle will only be called once after scroll stops for 1000 milliseconds. In other words, the event handler Handle has not been executed during the continuous triggering of the Scroll event.

Principle through the timer to delay the callback function. If the callback continues within the specified time and the previous timer is found, clear the timer and reset the timer

It can also be called using Lodash

// Avoid costly calculations while the window size is in flux.
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 
// Invoke `sendMail` when clicked, debouncing subsequent calls.
jQuery(element).on('click', _.debounce(sendMail, 300, {
  'leading': true.'trailing': false
}));
 
// Ensure `batchLog` is invoked once after 1 second of debounced calls.
var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000}); varsource = new EventSource('/stream');
jQuery(source).on('message', debounced);
 
// Cancel the trailing debounced invocation.
jQuery(window).on('popstate', debounced.cancel);
Copy the code

The throttle

If the Scroll event is triggered continuously, the Handle function is not executed immediately but only once every 1000 milliseconds.

function _throttle(fn,wait,time){ var previous = null; Var timer = null;return function(){
        var now = +new Date();

        if(! previous) previous = now; // If the difference between the last execution time and the current execution time is greater than the set execution interval, the active executionif(now - previous > time){ clearTimeout(timer); fn(); previous = now; // Immediately after executing the function, record the current time}else{
            clearTimeout(timer);
            timer = setTimeout(function(){
                fn();
            },wait); }}}function _log(){console.log(1)} window.onscroll = _throttle(_log,500,2000)Copy the code

Principle Shake prevention is to change multiple execution into the last execution, throttling is to change multiple execution into only one execution within a specified time. Generally, the timer is not reset

We’re throttling the scroll event on the moving end

handleScroll/* eslint-disable max-len */ const LOAD_OFFSET = 200; const needLoad = ((document.documentElement.scrollTop || document.body.scrollTop) + document.documentElement.clientHeight) > (document.body.scrollHeight - LOAD_OFFSET);if(needLoad) { this.loadmore(); }}Copy the code

A judgment will be given, if the top height of the scroll + enable area > the scroll height – starting point will be the data request, of course, you can also use setTimeout for processing

The dome looks like this: var canRun =true;
document.getElementById("throttle").onscroll = function() {if(! CanRun){// Check whether idle, if executing, then directlyreturn
        return;
    }

    canRun = false;
    setTimeout(function(){
        console.log("Function throttling");
        canRun = true;
    }, 300);
};
Copy the code

Of course, using LoDash is a best practice


jQuery(window).on('scroll', _.throttle(updatePosition, 100));
 
// Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
 
// Cancel the trailing throttled invocation.
jQuery(window).on('popstate', throttled.cancel);
Copy the code

Combined with Application Scenarios

  • throttle

    • Click the mouse repeatedly to trigger the mousedown(trigger only once per unit of time)
    • Listen for rolling events, such as whether to slide to the bottom to automatically load more, and throttle
    • touchmove
    • resize
  • debounce

    • input, keyup