防抖和节流啥区别,实现一个防抖和节流

Posted NsNe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了防抖和节流啥区别,实现一个防抖和节流相关的知识,希望对你有一定的参考价值。

防抖

在一定时间内执行一次,如果在此时间内再次触发,则重新计时

const debounce = (func, timeout, immediate = false) => {
  let timer = null;
  return function (...args) {
    if (!timer && immediate) {
      func.apply(this, args);
    }
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  }
}

节流

在一定时间内执行一次,如果在此时间内再次触发,则会拦截不执行

const throttle = (func, timeout) => {
  let timer = null;
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        timer = null;
        func.apply(this, args);
      }, timeout);
    }
  }
}

以上是关于防抖和节流啥区别,实现一个防抖和节流的主要内容,如果未能解决你的问题,请参考以下文章