preface

This article first introduces the two methods in the plug-in library underscore. Js, and then encapsulates the anti-shake throttling functions required by your project for your personal needs

_.debounce(function, wait, [immediate])

Plugin library package anti – shake function, there are three parameters are respectively

  • functionIs the function to be performed to stabilize
  • waitThe value is the time of the anti-shake interval in milliseconds
  • immediateParameters fortrueThe first time the incoming is triggeredfunctionExecuted immediately

_.throttle(function, wait, [options])

The plug-in library encapsulates the throttling functions respectively

  • Function is the function to be throttled

  • Wait is the throttling interval time in milliseconds

  • If {leading: false} is passed, the first execution is disabled. If {leading: false} is passed, the last execution is disabled

Both functions are called if you want to cancel them.cancel()methods

encapsulation

Image stabilization function

introduce

Time corresponding function after a period of time to perform, if called again in this period of time, is to calculate the execution time When scheduled time does not call this function again, executive function (similar to have to belong to the king of glory, frequently when click will have to terminate the operation, only waiting for the response time will have to trigger the complete operation)

Application scenarios

  • Scroll Event The scroll is triggered
  • The search box enters the query
  • Form validation
  • Button submission time
  • Browser window zoom,resize event

encapsulation

Because the underscore. Js package is so large that using only these two methods would take too long to load when the user enters the first entry page, making the user experience very poor, so we learn to encapsulate the function ourselves

 1function debounce(func, wait, immediate) {
 2  // Declare the timer and return parameters
 3  var timeout, result
 4  // Declare the return function
 5  let decounced = function ({
 6    // Get the this of the execution event to change the this direction of the passed func
 7    let _this = this
 8    // Get the time event object image of e that executes the function
 9    let args = arguments
10    // Important: If the event is triggered frequently, it will stop and reset the timer first. Only when the wait time is not executed, can the executed line be triggered to send func, so as to achieve the anti-shake effect
11    timeout && clearTimeout(timeout)
12    // Determines if immediate is true to execute the function immediately
13    if (immediate) {
14      // I automatically pay, therefore I am therefore underpaid. Therefore, I am therefore underpaid
15      letcallNow = ! timeout16      // Clear itself after assigning timeout a timer to wait so that timeout is null and callNow is true to execute the function passed in
17      timeout = setTimeout(() = > {
18        timeout = null
19      }, wait);
20      // callNow is true because there was no timer the first time, then the incoming execution func is called, but the incoming execution function is not fired if the timer is not destroyed
21      if (callNow) result = func.apply(_this, args)
22    } else {// If not, use the default anti-shake function
23      // Define the wait time to execute the timer
24      timeout = setTimeout(() = > {
25        // Call native JS apply to change this to point to and assign the parameter passed to get the object of event e
26        func.apply(_this, args)
27      }, wait);
28    }
29    return result
30  }
31  // Encapsulate stop cancek operation
32  decounced.cancel = function ({
33    // Pause and reset the timer
34    clearTimeout(timeout)
35    // Clear the timer
36    timeout = null
37  }
38  return decounced
39}
40}
Copy the code

Throttling function

introduce

If you continue to trigger events, only perform one event at a time (like the 98K shot, which is a frequent click to fire but 98K will only fire at fixed intervals).

Application scenarios

  • DOM element drag function implementation
  • Shooting game
  • Calculate the distance the mouse moves
  • Listen for scroll events

encapsulation

Because I feel that the current project does not need too complicated throttling function here, I have encapsulated the relatively simple anti-shake function

 1         function thorttle(func, wait{
 2            // Declare _this and args below change this to point to and get the passed func function
 3            let _this, args;
 4            let old = 0;
 5            return function ({
 6                _this = this
 7                args = arguments
 8                // Get the current timestamp when the first function is fired
 9                let now = new Date().valueOf();
10                Wait until func is passed in if the current time minus the timestamp of the previous operation is greater than the timestamp passed in
11                if (now - old > wait) {
12                    // Execute the function immediately since the first time the old timestamp is 0,
13                    func.apply(_this, args)
14                    // Record the current timestamp and assign it to odL (judge variable)
15                    old = now
16
17                }
18            }
19        }
Copy the code