防抖(debounce)和节流(throttle)

防抖(debounce)

当调用动作触发一段时间后,才会执行该动作,若在这段时间间隔内又调用此动作则将重新计算时间间隔

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)

预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新的时间周期

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)

猜你喜欢

转载自www.cnblogs.com/zhoulixue/p/11106010.html