Image stabilization function

  • How it works: The callback is executed n seconds after the event is triggered. If it is triggered again within n seconds, the timer is reset

    const debounce = (fn,delay) = > {
        let timer = null;
        return (. arg) = > {
            clearTimeout(timer);
            timer = setTimeout(() = >{
                fn.apply(this,args);
            },delay)
        }
    }
Copy the code

Applicable scenario

  • Button submission scenario: Prevents multiple button submissions and only performs the last submission
  • Server validation scenario: Form validation requires server coordination, only a sequence of input events for the last time, and search for associative words similar to the live environment please use Lodash. Debounce

Throttling function

  • Specifies that a function can fire only once in a specified period of time. If it fires multiple times in this unit of time, only one time will take effect
    const throttle = (fn,delay=500) = >{
        let flag = true;
        return (. args) = > {
            if(! flag)return
            flag = false;
            setTimeout(() = >{
                fn.apply(this,args)
                flag = true
            },delay)
        
        }
    
    }
    
Copy the code

Applicable scenario

  • Drag scenario: execute only once in a fixed time to prevent high-frequency words from triggering position changes
  • Zoom the scene and monitor browser resize
  • Animated scenes to avoid performance problems caused by multiple animation triggers in a short time