Shake and throttling

This is the fifth day of my participation in the More text Challenge. For details, see more text Challenge

Why use anti-shake throttling? In front end development, some user behaviors will frequently trigger event execution, and for DOM operation, resource loading and other performance consuming processing, it is likely to cause interface stalling, or even browser crash. Throttling and debounce were created to address similar needs.

Image stabilization (debounce)

Function stabilization is when a function needs to be fired frequently, it is executed only once when there is enough idle time. It’s like a bus driver waits for everyone to board before closing the door. Instead of just one person coming up and triggering the door once, he would wait for a few more people to come up and then trigger the door

Scenario :(stop execution for a period of time after time triggers frequently)

  • Real-time Search (KEYup)
  • Drag (mousemove)
  • Verify the input of mobile phone number and email
  • Window size Resize. Just calculate the window size after the window adjustment is complete. Prevents duplicate rendering.

We take Baidu search box after the completion of the input pause for a period of time will enter ajax request as an example, we realize the input box to stop the input and then print

// Use higher-order functions, wrapped with closures<! --<script src=".. /.. /plugin/helpers.js"></script> -->
   
        let oInp = document.getElementById('inp')
        let timer = null
        const debounce = (handler, delay) = > {
            let timer = null // Save the same timer with a closure
            return () = > {
                let _self = this // Take debounce and execute this in scope
                let _arg = arguments // Use closures to hold the parameter array
                clearTimeout(timer) // Continue to execute the function, continue to clear the timer
                timer = setTimeout(() = > {
                    handler.apply(_self, _arg) // Use apply to point to the object that calls debounce, equivalent to _this.handler(args);
                }, delay)
            }
        }
        let shouValue = (e) = > {
            console.log(e,this.value)
        }
        oInp.oninput = debounce(shouValue, 1000);

Copy the code

The throttle (throttle)

Function throttling is the process of preempting a function to be executed only for periods greater than or equal to the execution period. It’s like water drops have to weigh a certain amount before they fall.

Scenario: CON(no matter how often the time is triggered, at least every once in a while instead of waiting for the event to finish firing)

Resize the window and click on the mousedown

I have two ideas at the moment:

  • Use the timer, timed to execute after one second, but in the 1s of the call, not let his timer reset, will not affect the current result, or continue to wait for that 1s, wait for 1 second to trigger (will there be a stop operation or trigger)
// Make sure to execute once in a period of time
        const throttle = (handler, time) = > {
            let timer
            return () = > {
                if (timer) {
                    return // If a timer is not cleared, return it and do nothing
                }
                let _self = this // Select this from the throttle scope
                let _arg = arguments // Use closures to hold the parameter array
                timer = setTimeout(() = > {
                    handle.apply(_self, _arg)
                    timer = null
                }, time)
            }
        }
        // Triggers the event
        window.onresize =  () = > handle()
        // Processing function
        let test = () = >console.log("a")
        // Call throttle function to pass the parameters
        let handle = myPlugin.throttle(test, 2000)

Copy the code
  • With a timestamp, it executes immediately, but it takes a while for the next execution
 const throttle = (handler, time) = > {
            let t 
            return () = > {
                let _self = this // Select this from the throttle scope
                let _arg = arguments // Use closures to hold the parameter array
                if(! t ||Date.now() - t >= time ) {
                    handler.apply(_self , _arg );
                    t = Date.now(); // The current timestamp obtained}}}window.onresize =  () = > handle()
        let test = () = >console.log("a")
        let handle = myPlugin.throttle(test, 2000)

Copy the code

To determine the difference between the two methods, we can combine the two methods of throttling simply by deciding whether we need to do it immediately or not

// Make sure to execute only once at a time
      constthrottle = (handler, time, immediately) = > {
            if (immediately === undefined) {
                immediately = true // The judgment needs to be executed immediately
            }
            if (immediately) {
                let t
                return () = > {
                    let _self = this // Select this from the throttle scope
                    let _arg = arguments // Use closures to hold the parameter array
                    if(! t ||Date.now() - t >= time) {
                        handler.apply(_self, _arg);
                        t = Date.now(); // The current timestamp obtained}}}else {
                let timer
                return () = > {
                    if (timer) {
                        return // If a timer is not cleared, return it and do nothing
                    }
                    let _self = this // Select this from the throttle scope
                    let _arg = arguments // Use closures to hold the parameter array
                    timer = setTimeout(() = > {
                        handle.apply(_self, _arg)
                        timer = null
                    }, time)
                }
            }

        }
        window.onresize = () = > handle()
        let test = () = > console.log("a")
        let handle = myPlugin.throttle(test, 2000.true)

Copy the code