js 记录 debounce与throttle

2019-03-26  本文已影响0人  Micro同学

debounce~

三参数
debounce (func, wait, immediate) {
  let timeout
  return () => {
    let context = this
    let args = arguments
    let later = () => {
      timeout = null
      if (!immediate) {
        func.apply(context, args)
      }
    }
    let callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) {
      func.apply(context, args)
    }
  }
}

实际使用时可以:

let testFunction = debounce(() => {
  // Balalalala
}, 250)
window.addEventListener('resize', testFunction)

or

监听对象.addEventListener('click', debounce(() => {
  console.info(new Date().toUTCString())
}, 3000))
二参数
debounce (fn, delay) => {
  let timer
  return function() {
    let self = this
    let args = arguments
    clearTimeout(timer)
    timer = setTimeout(() => func.apply(self, args), delay)
  }
}

throttle~

throttle (fn, limit) => {
  let inThrottle
  return () => {
    let args = arguments
    let self = this
    if (!inThrottle) {
      fn.apply(self, args)
      inThrottle = true
      setTimeout(() => {
        inThrottle = false
      }, limit)
    }
  }
}

实际使用

监听对象.addEventListener('click', throttle(() => {
  return console.log(new Date().toUTCString())
}, 1000))

如果上来第一次需要触发 可以加个开关变量

let isOn = true
function throttle (fn, limit) {
  let inThrottle
  return () => {
    let args = arguments
    let self = this
    if (isOn) {
      isOn = false
    } else if (!inThrottle) {
      fn.apply(self, args)
      inThrottle = true
      setTimeout(() => {
        inThrottle = false
        isOn = true
      }, limit)
    }
  }
}

先记录一下...备用

上一篇 下一篇

猜你喜欢

热点阅读