js 的防抖节流

防抖

性能优化方案,防抖用于减少函数请求次数,对于频繁的请求,只执行这些请求的最后一次。

基础版本

function debounce(func, wait = 300){
  let timer = null;
  return function(){
    if(timer !== null){
      clearTimeout(timer);
    }
    timer = setTimeout(func.bind(this),wait);
  }
}

改进版本添加是否立即执行的参数,因为有些场景下,我们希望函数能立即执行。

/**
 * @param {function} func - 执行函数
 * @param {number} wait - 等待时间
 * @param {boolean} immediate - 是否立即执行
 * @return {function}
 */
function debounce(func, wait = 300, immediate = false){
  let timer, ctx;
  let later = (arg) => setTimeout(()=>{
    func.apply(ctx, arg)
    timer = ctx = null
  }, wait)
  return function(...arg){
    if(!timer){
      timer = later(arg)
      ctx = this
      if(immediate){
        func.apply(ctx, arg)
      }
    }else{
      clearTimeout(timer)
      timer = later(arg)
    }
  }
}

使用

let scrollHandler = debounce(function(e){
  console.log(e)
}, 500)
window.onscroll = scrollHandler

节流

性能优化方案,节流用于减少函数请求次数,与防抖不同,节流是在一段时间执行一次。

/**
 * @param {function} func - 执行函数
 * @param {number} delay - 延迟时间
 * @return {function}
 */
function throttle(func, delay){
  let timer = null
  return function(...arg){
    if(!timer){
      timer = setTimeout(()=>{
        func.apply(this, arg)
        timer = null
      }, delay)
    }
  }
}

使用 

let scrollHandler = throttle(function(e){
  console.log(e)
}, 500)
window.onscroll = scrollHandler

  

posted @ 2020-08-03 19:10  小魏code  阅读(171)  评论(0编辑  收藏  举报