美文网首页
前端笔试题 节流防抖的含义及代码

前端笔试题 节流防抖的含义及代码

作者: 江火渔枫 | 来源:发表于2022-10-11 22:46 被阅读0次

节流 节流指的都是某个函数在一定时间间隔内只执行第一次回调。

const throttle = (cb, wait=3000) => {
  let timeId;
  return (...args) => {
    if( timeId ) return;
    timeId = setTimeout(() => {
      cb.apply(this, args);
      timeId = undefined;
    }, wait)
  }
}

防抖 无视短时间内重复回调,限流是在某段时间内只执行首次回调,而防抖动通常是只执行末次回调。

function debounce(cb, wait = 3000) {
  let timer = null

  return (...args) => {
      if (timer) clearTimeout(timer)

      timer = setTimeout(() => {
        timer = null;
        cb.apply(this, args)
      }, wait)
  }
}

节流防抖
前端节流(throttle)和防抖动(debounce) - 简书 (jianshu.com)

相关文章

网友评论

      本文标题:前端笔试题 节流防抖的含义及代码

      本文链接:https://www.haomeiwen.com/subject/pdazartx.html