Stabilizer (Debounce) and the throttle (Throttle)

Image Stabilization (debounce)

When you call the action triggered a period of time, before the implementation of the action will be recalculated if they call this action during this time interval time interval .

 

function debounce(method, timeout, context) {
  return function() {
    var args = arguments
    clearTimeout(method.timer)
    method.timer = setTimeout(() => {
      method.apply(context, args)
    }, timeout)
  }
}
function handleResize() {
  console.log('resize')
}
window.onresize = debounce(handleResize, 500, window)

 

Throttle (throttle)

Performing a pre-set period, the time when the call operation is not less than the execution period of the operation is executed, then the next time a new period .

function throttle(method, timeout, context, cycle) {
  var startTime = +new Date()
  return function() {
    var args = arguments
    var currTime = +new Date()
    clearTimeout(method.timer)
    if (currTime - startTime >= cycle) {
      method.apply(context, args)
      startTime = currTime
    } else {
      method.timer = setTimeout(() => {
        method.apply(context, args)
      }, timeout)
    }
  }
}
function handleResize() {
  console.log('resize')
}
window.onresize = throttle(handleResize, 500, window, 2000)

 

Guess you like

Origin www.cnblogs.com/zhoulixue/p/11106010.html