手写 节流和 防抖

53 阅读1分钟
// 节流
const throttle = (f,time) => {
  let timer = null
  return (...args) => {
    if(timer) {return}
    f.call( undefined , ...args )
    timer = setTimeout (() => {
      timer = null
     },time)
  }
}
let f = throttle(() => console.log('hi'),3000)
f()
// 防抖
const debounce = ( f , time ) => {
  let timer = null
  return (...args) => {
    if(timer !== null ) {
      clearTimeout(timer)
    }
    timer = setTimeout( () => {
      f.call( undefined , ...args )
      timer = null
      
    } , time)
  }
}