“This is the 14th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

At present, many of our front-end projects are running under the browser, so there are a lot of human-computer interaction operations, so we can have a high frequency of events click on the button, so that the browser has a certain performance consumption

What is a throttling function

Throttling Throttling means to save the flow of water. Like a faucet running water, we can manually reduce the flow of water (for a certain period of time), but it will continue to flow.

That’s the main purpose of our cost-cutting

In fact, function throttling, simply speaking, is to prevent a function from being called consecutively within a very short time interval, only when the last function has been executed after the specified time interval, the next function can be called.

Common scenarios are as follows:

  • DOM element drag and drop implementation (Mousemove)
  • Search for Associations (KeyUp)
  • Calculate the distance of mouse movement (Mousemove)
  • Canvas Drawing Board (Mousemove)
  • Shooter mouseDown/KeyDown events (only one shot per unit of time)

The core idea of throttling function

Function throttling principle is very simple, it is estimated that we have thought of, that is timer.

When I trigger an event, I only trigger the event once per unit of time. If the event is triggered and the same event is triggered again, I ignore subsequent events until the timing of the first event ends

The difference between throttling function and anti – shake function

  • Throttling function: the function is executed only once in n seconds. If multiple events are triggered during this period, subsequent events are ignored until the timing of the first event ends
  • Struggle function: within n seconds after the trigger function, if it is triggered several times, the previous event will be closed until the end of the last event timing

implementation

/ * * *@param {function} func- Executes the function *@param {number} delay- Delay time *@return {function}* /
function throttle(func, delay){
  let timer = null
  return function(. arg){
    // If the timer does not exist, the next thing will not be executed
    if(! timer){ timer =setTimeout(() = >{
        func.apply(this, arg)
        // Why null?
        // Let's rethink the concept of throttling functions
        If multiple events are fired, ignore subsequent events until the timing of the first event expires
        timer = null
      }, delay)
    }
  }
}
Copy the code

use

let scrollHandler = throttle(function(e){
  console.log(e)
}, 500)
window.onscroll = scrollHandler
Copy the code