手写系列 - debounce、throttle

121 阅读1分钟
function debounce(fn, wait) {
  let timer = null
  return fucntion(){
    let context = this;
    let args = arguments;

    if (timer) {
      clearTimeout(timer)
      timer = null;
    }

    timer = setTimeout(() => {
      fn.apply(context, args)
    }, wait)
  }
}


function throttle(fn, delay) {
  let currTime = Date.now()

  return function () {
    let context = this;
    let args = arguments;
    let nowTime = Date.now()

    if (nowTime - currTime >= delay) {
      currTime = Date.now()
      return fn.apply(context, args)
    }
  }

}