防抖节流

132 阅读1分钟

基础题

  • 防抖
  • 节流

防抖

覆盖式,以最后一次优先
场景:button 提交

const debounce = (fn, wait) => {
  let timer = null;
  return (...args) => {
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, wait)
  }
}
// test
const fn = (a) => {console.log(a)}
const update = debounce(fn, 1000);
for(let i in [1, 2, 3]) {update(i)} // 2

节流

阻隔式,以第一次优先
场景:input 搜索

const throttle = (fn, wait) => {
  let timer = null;
  return (...args) => {
    if(!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args)
        timer = null;
      }, wait)
    }
  }
}
// test
const fn = (a) => {console.log(a)}
const update = throttle(fn, 1000);
for(let i in [1, 2, 3]) {update(i)} // 0