节流函数 防抖函数

防抖函数(debounce)

当持续触发事件时,在一定的时间段内没有触发事件,事件才会让函数调用一次,如果一定的你时间内触发事件,就重新开始计算

实现

// debounce_.js
function debounce_ (fn, delay) {
  let timer = null
  return function () {
    if (timer !== null) clearTimeout(timer)
    timer = setTimeout(fu, delay)
  }
}
function handleEvent () {
  console.log('我来了')
}
window.addEventListener('scroll', debounce_(handleEvent, 1000))

节流函数(throttle)

当持续触发事件时,在一定时间内触发保证只调用一次处理事件

function throttle (fn, delay) {
  let prev = Date.now()
  return function () {
    let now = Date.now()
    let seft = this
    let args = arguments
    if (now - prev >= delay) {
      fn.apply(seft, args)
      prev = Date.now()
    }
  }
}
function handleEvent () {
  console.log('我来了')
}
window.addEventListener('scroll', throttle(handleEvent, 1000))

你可能感兴趣的:(节流函数 防抖函数)