Click events, mouse movement events, window scrolling events, etc., are inevitable during front-end development, but they are not expected to be executed frequently. This is where we need to optimize these event handlers with the help of anti-shake and throttling.

Before throttling and anti-shake treatment, as shown in the figure below

const box = document.getElementById('box')
const domX = document.querySelector('.x_axis')
const domY = document.querySelector('.y_axis')
const domCount = document.querySelector('.counter')
const domTime = document.querySelector('.time')

let counter = 0       / / counter
let timer = 0     / / timer
let timeID = null  / / timer
box.addEventListener('mousemove'.function (e) {
  if (timer >= 3) {
    clearInterval(timeID)
    return
  }
  if (counter === 0) {
    timeID = setInterval(() = > {
      timer += 1
      domTime.innerText = ` Time:${timer} S`
    }, 1000)
  }
  counter += 1
  domX.innerText = X-axis coordinates:${e.screenX} px`
  domY.innerText = Y-axis coordinates:${e.screenY} px`
  domCount.innerText = 'Trigger times:${counter}Time `
})
Copy the code

Debounce

If the event is triggered again within n seconds, the time will be reset with the current triggered time node as the starting point.

The anti – shake function can be executed immediately or not immediately.

  1. The immediate execution case means that the event function executes immediately after the event is fired and then does not execute if the event is fired again within a specified period of time.

    function debounce (func, wait) {
      let timeout = null // Timer
      return function () {
        const _this = this
        const args = arguments
        // If a timer for a previous event already exists at a specific time, the previous timer needs to be cleaned up first
        if (timeout) clearTimeout(timeout)
        constcallNow = ! timeout// reset the timer
        timeout = setTimeout(() = > {
          timeout = null
        }, wait)
        if (callNow) func.apply(_this, args)
      }
    }
    Copy the code
  2. Deferred execution is when an event is delayed for some time after it has been triggered.

    function debounce (func, wait) {
      let timeout = null
      return function () {
        const _this = this
        const args = arguments
        if (timeout) clearTimeout(timeout)
        // The event handler will delay the execution of an event
        timeout = setTimeout(() = > {
          func.apply(_this, args)
        }, wait)
      }
    }
    Copy the code

  • Merges later-execution and immediate-execution anti-shake functions

    function debounce (func, wait, immdiate) {
      let timeout = null
      return function () {
        const _this = this
        const args = arguments
    
        if (timeout) clearTimeout(timeout)
        if (immediate) {
          constcallNow = ! timeout timeout =setTimeout(() = > {
            timeout = null
          }, wait)
          if (callNow) func.apply(_this, args)
        } else {
          timeout = setTimeout(() = > {
            func.apply(_this, args)
          }, wait)
        }
      }
    }
    Copy the code

The throttle

Throttling is a partial optimization of performance by reducing the frequency of event departure for n seconds,

  1. Use timestamps to control the frequency of the trigger

    function throttle (func, wait) {
      let previous = 0
      return function () {
        const now = new Date.now()
        const _this = this
        const args = arguments
        if (now - previous > awit) {
          func.apply(_this, atgs)
          previous = now
        }
      }
    }
    Copy the code
  2. Use timers to control the frequency of the trigger

    function throttle (func, wait) {
      let timeout = null
      return function () {
        const _this = this
        const args = arguments
        if(! timeout) { timeout =setTimeout(() = > {
            timeout = null
            func.apply(_this, args)
          }, wait)
        }
      }
    }
    Copy the code

  • Merge version
    / * * *@desc Function throttling@param {*} Func Func function *@param {*} Wait Wait number of milliseconds to delay execution *@param {*} Type 1 table timestamp version, 2 table timer version */
    function throttle(func, wait, type) {
      let previous = 0;
      let timeout = null;
      if (type === 1) {
        previous = 0;
      } else if (type === 2) {
        timeout = null;
      }
      return function () {
        const _this = this;
        const args = arguments;
        if (type === 1) {
          const now = Date.now();
          if(now - previous > wait) { func.apply(_this, args); previous = now; }}else if (type === 2) {
          if(! timeout) { timeout =setTimeout(() = > {
              timeout = null; func.apply(_this, args); }, wait); }}}; }Copy the code