preface

Function anti – shake and throttling, this knowledge is asked in the interview probability is relatively high.

Image stabilization

Non-immediate version of the anti-shake can be understood as n time after the execution of a function. Now version of the anti – shake is immediately executed once function.

The realization of anti – shake

@param {Function} @param {Number} @param {Number}waitNumber of milliseconds * @param {Boolean} immediatetrueIndicates immediate execution.false*/ is not executed immediatelyfunction debounce(func, wait, immediate) {
  let timeout
  return function () {
    let context = this
    let args = arguments
    if (timeout) {
      clearTimeout(timeout)
    }
    if (immediate) {
      letcallNow = ! timeout timeout =setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) {
        typeof func === 'function' && func.apply(context, args)
      }
    } else {
      timeout = setTimeout(() => {
        typeof func === 'function' && func.apply(context, args)
      }, wait)}}}Copy the code

The throttle

Throttling can be thought of as executing a function every n times.

Implementation of throttling

/** * @param {Function} @param {Number}wait* @param {Boolean}type trueRepresents the timestamp version,falseIndicates timer */function throttle(func, wait.type) {
  let previous
  let timeout
  if (type) {
    previous = 0
  } else {
    timeout
  }
  return function () {
    let context = this
    let args = arguments
    if (type) {
      let now = Date.now()
      if (now - previous > wait) {
        typeof func === 'function' && func.apply(context, args)
        previous = now
      }
    } else {
      if(! timeout) { timeout =setTimeout(() => {
          timeout = null
          typeof func === 'function' && func.apply(context, args)
        }, wait)}}}}Copy the code

The difference between anti-shake and throttling

Use the text box to input text to demonstrate, if the time is set to 1s, the user continuously input text, if it is not immediately perform the anti-shake is stopped after 1s function execution, only execute once, if it is immediately perform the anti-shake is immediately perform the function execution, only execute once. Throttling is the execution of a function every second, possibly multiple times, during user input.

The difference between anti-shake and throttling calls

The following code calls both the stabilization function and the throttling function 10 million times, but the stabilization function is only executed once, while the throttling function is executed many times.

let debounceCallback = debounce(function () {
  console.log('debounceCallback')}, 1000,false)

for (let i = 0; i < 10000000; i++) {
  debounceCallback()
}

let throttleCallback = throttle(function () {
  console.log('throttleCallback')}, 1000,false)

for (let i = 0; i < 10000000; i++) {
  throttleCallback()
}
Copy the code

Thanks for reading!

Need to add wechat communication, can leave a message!