手写js函数节流与抖动

函数防抖的实现

函数抖动:在事件被触发 n 秒后再执行回调,若是在这 n 秒内事件又被触发,则从新计时。
// 函数防抖的实现
function debounce(fn, wait) {
  var timer = null

  return function () {
    var context = this,
      args = arguments

    // 若是此时存在定时器的话,则取消以前的定时器从新记时
    if (timer) {
      clearTimeout(timer)
      timer = null
    }

    // 设置定时器,使事件间隔指定事件后执行
    timer = setTimeout(() => {
      fn.apply(context, args)
    }, wait)
  }
}
// test
var debounceRun = debounce(function () {
  console.log(123)
}, 2000)
// 只有当鼠标移动中止后2s打印123
window.addEventListener('mousemove', debounceRun)

函数节流的实现

函数节流:规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,若是在同一个单位时间内某事件被触发屡次,只有一次能生效。
function throttle(fn, delay) {
  var preTime = Date.now()
  return function () {
    var nowTime = Date.now()
    if (nowTime - preTime >= delay) {
      preTime = nowTime
      fn.apply(this, arguments)
    }
  }
}
// test
var throttleRun = throttle(() => {
  console.log(123)
}, 2000)
// 不停的移动鼠标,控制台每隔2s就会打印123
window.addEventListener('mousemove', throttleRun)
相关文章
相关标签/搜索