Colleagues share the anti-shaking throttling and application in the project, I think it is ok, and forwarded to ~~~

This is the fourth day of my participation in the August More Text Challenge. For details, see “August More Text Challenge”.

If the throttle

What is shockproof throttling?

Debounce: Prevents repeated clicks from triggering events (the last person is in charge, no matter how many times you trigger a callback within a certain period of time, I only consider the last callback)

Application scenario:

  1. Buttons such as login and texting need to be stabilised to prevent users from clicking too quickly and sending multiple requests
  2. When resizing the browser window, the number of resize times is too frequent, resulting in excessive calculation. At this time, it needs to be in place once, which is used to stabilize
  3. The text editor saves in real time, when no changes are performed for one second
  4. .

Code to achieve points: set a timer, through the closure, catch the timer variable, control the timer added and deleted

// Non-immediate execution version: the function is not executed immediately after the event is fired, but after n seconds. If the event is fired within n seconds, the execution time of the function is recalculated

function debounce(fn, time) {
      let timer
      return function () {
          const args = arguments
          if (timer) clearTimeout(timer)
          timer = setTimeout(() = > {
              fn.call(this, args)
          }, time)
      }
  }



// Immediate execution version: the function is executed immediately after the event is fired. If the event is not fired for n seconds, the effect of the function will continue

function debounce(fn, time) {
  let timer;
  return function () {
    const ctx = this;
    const args = arguments;
    letcallNow = ! timer;if (timer) clearTimeout(timer);
    timer = setTimeout(() = > {
      timer = null;
    }, time)

    if (callNow) fn.call(ctx, args);
  };
}



// Combine version

/ * * *@desc Function anti - shaking *@param Fn functions *@param Wait Indicates the number of milliseconds that the execution is delayed@param Immediate true Indicates that the table is executed immediately. False indicates that the table is not executed immediately. */

function debounce (fn, wait, immediate) {
  let timer
  return function () {
    const ctx = this
    const args = arguments
    if (timer) clearTimeout(timer)
    // Execute immediately
    if (immediate) {
      constcallNow = ! timer timer =setTimeout(() = > {
        timer = null
      }, wait)
      if (callNow) fn.call(ctx, args)
    } else {
      timer = setTimeout(() = > {
        fn.call(ctx, args)
      }, wait)
    }
  }
}
Copy the code

Throttling: Specifies that a task is executed only once in a specified interval (no matter how many callbacks you trigger within a certain period of time, I will only recognize the first callback and respond when the timer ends).

Code implementation points: the main points of the timer version and timestamp version

Scene:

  1. Scroll event, the position information is calculated every second
  2. The browser plays events and calculates progress information every second
  3. Real-time search and send requests to the Input box display a drop-down list, every second to send a request (can also do anti-shake)
// Timer version: the function is not executed immediately, but is executed every x seconds, and is executed again after the event is stopped
function throttle(fn, time) {
      let timeout;
      return function () {
          const args = arguments
          if(! timeout) { timeout =setTimeout(() = > {
                  fn.call(this, args)
                  timeout = null}, time); }}}// Timestamp version: The function executes immediately and every x seconds for the duration of the event

function throttle(fn, time) {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if(now - previous > time) { fn.apply(context, args); previous = now; }}}/ / version
/ * * *@desc Function throttling@param Func function *@param Wait Indicates the number of milliseconds that the execution is delayed@param Type 1 table timestamp version, 2 table timer version */

function throttle(fn, time ,type) {
    if(type===1) {let previous = 0;
    } else if(type===2) {let timeout;
    }

    return function() {
        let context = this;
        let args = arguments;
        if(type===1) {let now = Date.now()
            if(now - previous > time) { fn.apply(context, args); previous = now; }}else if(type===2) {if(! timeout) { timeout =setTimeout(() = > {
                    timeout = null;
                    fn.apply(context, args)
                }, time)
            }
        }
    }
}
Copy the code
  1. How it is used in vUE projects

Custom instruction mode

// Combine the third-party library Lodash

/ stabilization throttling * * * * 1. According to the modifier is judge stabilization or throttling * using method is as follows. * (1) v - debounceOrThrottle debounce stabilization. * (2) v - debounceOrThrottle throttle orifice * 2. * (1) V-debounceorThrottle :{wait: 2000,leading:false,trailing:true}.debounce *@params Wait Delay time *@params Leading: True (false) specifies that the call is made before (after) [shaking/throttling] starts *@params Trailing: true(false) specifies that the call is trailing after (before) the start of [shaking/throttling]

import _debounce from 'lodash/debounce'
import _throttle from 'lodash/throttle'
let fn = null

export default {
  inserted: function(el, binding) {
    const { modifiers, arg } = binding
    const time = 2000
    let _arg = {}
    if (arg) _arg = eval('(' + arg + ') ')
    const { wait = time, leading = true, trailing = false } = _arg
    if (modifiers.throttle) {
      / / throttling
      fn = _throttle(binding.value, wait, {
        leading,
        trailing
      })
    } else {
      / / image stabilization
      fn = _debounce(binding.value, wait, {
        leading,
        trailing
      })
    }
    el.addEventListener('click', fn)
  },

  //unbind: called only once, when the directive is unbound from the element
  unbind: function(el) {
    fn && el.removeEventListener('click', fn)
  }
}
Copy the code