关于javascript:手写js函数节流与抖动

3次阅读

共计 773 个字符,预计需要花费 2 分钟才能阅读完成。

函数防抖的实现

函数抖动:在事件被触发 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)
正文完
 0