export default class ThrottleUtil {
    /** * throttling * Only executes the function once in a while. *@param Delay Determine time *@param Action Actual method *@param * {* toggleLastArg // Boolean. The default value is false (only the first click) *} *@returns {Function} Callback, callback the actual method */
    static throttle = (delay, action = () => {}, options) = > {
        let last = 0;
        consttoggleLastArg = !! (options && options.toggleLastArg);let toggleLastArgTimer = null;
        return function (. args) {
            if (toggleLastArgTimer) clearTimeout(toggleLastArgTimer);
            const curr = new Date().getTime();
            if (curr - last > delay) {
                action.call(this. args);// Call this for the external to get the correct this value
                last = curr;
            } else if (toggleLastArg) {
                toggleLastArgTimer = setTimeout(() = > {
                    action.call(this. args); }, delay); }}; }/** * Anti-shake * definition: after triggering the event for many times, the event handler only executes once, and is executed at the end of triggering operation * Principle: delay the processing function for delay operation, if the set delay comes, trigger the event again, then clear the last delay operation timer, re-timing. *@param Delay Determine time *@param Action Actual method *@returns {Function} Callback, callback the actual method */
    static debounce = (delay, action = () => {}) = > {
        let timer = null;
        return function (. args) {
            if (timer) {
                clearTimeout(timer);
            }
            timer = setTimeout(() = > {
                action.call(this. args);// Call this for the external to get the correct this value}, delay); }; }}Copy the code

Anti – shake and throttle difference


The simple way to think about it is,

  • Throttling is similar to playing games, continue to click the mouse to shoot, but will only be sent once in a certain time interval, can be launched at intervals, save resources (can be executed for many times);
  • For example, anti-shake is a high-risk operation. To prevent hand shake, cancel the previous operation and perform the last operation (only one operation).