This is the twenty-sixth day of my participation in the August Gwen Challenge.

JavaScript advanced

JavaScript Advanced (2)

JavaScript advanced (three) modular

JavaScript advanced (4) anti-shake

The throttle

They say throttling, but what exactly is throttling? In fact, the simple point is that you click a button many times, it will follow a certain interval of time. The essence is not the same as anti – shake, anti – jitter is the multiple execution into the last execution.

  • Let’s take a quick look at the code implementation:
// This is used to get the current timestamp

function now() {
    return new Date()
}

/** * underscore (@param {function} func: / @param {number} wait) /** ** underscore (@param {number} wait) * @param {object} options: * ignore the start function call, pass {leading: false} * ignore the end function call, pass {trailing: False} * Both cannot coexist, otherwise the function cannot be executed * @return {function} */
function (func, wait, options) {
    var context, args, result;
    var timeout = null;
    // The previous timestamp
    var previous = 0;
    if(! options) options = {};// Timer callback function
    var later = function () {
        previous = options.leading === false ? 0 : now();
        // Empty to prevent memory leaks, and for the following timer judgment
        timeout = null;
        result = func.apply(context, args);
        if(! timeout)context = args = null;
    };
    return function () {
        // Get the current timestamp
        var now = now();
        if(! previous && options.leading === false) previous = now;
        // Calculate the remaining time
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;
        if (remaining <= 0 || remaining > wait) {
            // If there is a timer, clear it to avoid a second callback
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            previous = now;
            result = func.apply(context, args);
            if(! timeout)context = args = null;
        } else if(! timeout && options.trailing! == false) {// Check whether the timer and trailing are set
            // If no, restart a timer
            // And cannot set leading and trailing at the same time
            timeout = setTimeout(later, remaining);
        }
        return result;
    };
};
Copy the code

Ok, so that’s a simple implementation version of throttling. A little bit complicated, but read a few more times, I believe you can see, the book read a hundred times its sense of self, believe in yourself.

Bye-bye, everybody. I’m Augus, a software developer who likes to screw around. END~~~