常见前端手写功能

1.防抖
//防抖
function debounce(fn, delay) {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}
//测试
function test() {
  console.log('run...')
}
const debounceTask = debounce(test, 1000)
window.addEventListener('scroll', debounceTask)
2.节流

function throttle(fn, delay) {
  let last = 0//上次触发时间 
  return function (...args) {
    const now = Date.now()
    if (now - last > delay) {
      last = now
      fn.apply(this, args)
    }
  }
}

//测试
function test() {
  console.log('run...')
}
const throttleTask = debounce(test, 1000)
window.addEventListener('scroll', throttleTask)

你可能感兴趣的:(常见前端手写功能)