手写节流、防抖

  • 节流:比如一个抢购按钮,用户在几秒内只能点击一次(就是技能冷却中)
const throttle = (fn ,time) => {
  let timer = null
  return ( ...args ) => {
    if(timer) {return}
    f.call(undefined, ...args)
    timer = setTimeout ( () => {
      timer = null
    }, time)
  }
}
  • 防抖:比如网页拖动,一直拖动网页内容格式就不会改变,停留下来才会改变(就是回城被打断)
const debounce = (fn ,time) => {
  let timer = null
  return (...args ) => {
    if (timer !===null) {
      clearTimeout(timer)  //打断
    }
    timer = setTimerout( () => {
      fn.call(undefined, ...args)
      timer = null
    },time}
  }
}

你可能感兴趣的:(手写节流、防抖)