有趣且重要的JS知识合集(5)防抖节流函数

41 阅读1分钟
 
/**
 * 防抖函数(常用于input框搜索情况)
 * @param {*} func 
 * @param {*} delay 
 * @param {*} immediate 
 * @returns 
 */
export function debounce(func, delay, immediate = true) {
  let timer = null
  return function(args) {
    let _this = this
    if (timer) {
      clearTimeout(timer)
    }
    if (immediate) {
      let now = !timer
      timer = setTimeout(() => {
        timer = null
      }, delay)
      now && func.call(_this, args)
    } else {
      timer = setTimeout(() => {
        timer = null
        func.call(_this, args)
      }, delay)
    }
  }
 }

 
/**
 * 节流函数(常用于onresize, onmouseover情况)
 * @param {*} func 
 * @param {*} delay 
 * @param {*} immediate 
 * @returns 
 */
export function throttle(func, delay, immediate = true) {
  let timer = null
  return function (args) {
    let _this = this
    if (!timer) {
      if (immediate) {
        func.call(_this, args)
        timer = setTimeout(() => {
          timer = null
        }, delay)
      } else {
        timer = setTimeout(() => {
          func.call(_this, args)
          timer = null
        }, delay)
      }
    }
  }
}