节流与防抖

防抖或是节流:限制函数的执行次数

  1. 防抖:在一定的时间间隔内,将多次触发变成一次触发;

  2. 节流:减少一段时间的触发频率;

防抖函数 (debounce)

const debounce = (fn, wait = 500) => {
 let timer = null
 return function (...args) {
   if (timer) clearTimeout(timer)
   timer = setTimeout(fn.bind(this), wait, ...args)
}
}

节流函数 (throttle)

const throttle = (fn, wait = 500) => {
 let timer = null
 return function(...args) {
   if (timer) return
   timer = setTimeout(fn.bind(this), wait, ...args)
   timer = null
}
}
 
posted @ 2022-05-10 11:48  这个名字没占用  阅读(21)  评论(0)    收藏  举报