Implemented using a simple shake closure (rpm)

// fn is a function to be executed
// wait is the time interval
const throttle = (fn, wait = 50) => {
  Once the execution time of the fn //
  let previous = 0
  // handle the throttle function returns the result as
  return function(...args) {
    // get the current time into a timestamp milliseconds
    let now = +new Date()
    // The last execution of a function of the current time and the comparison
    // is greater than the waiting time to put previous to the current time and perform the function fn
    if (now - previous > wait) {
      previous = now
      fn.apply(this, args)
    }
  }
}

// DEMO
// Perform throttle function returns a new function
const betterFn = throttle (() => console.log ( 'fn function performs'), 1000)
// performed once every 10 milliseconds betterFn functions, but only when the time difference is greater than 1000 will perform fn
setInterval(betterFn, 10)

  Transfer good fast hardware blog: principle and implementation https://www.muyiy.cn/blog/7/7.1.html#

Guess you like

Origin www.cnblogs.com/wilsunson/p/11578102.html