轻松理解节流防抖

153 阅读2分钟

节流

什么是节流,举个例子

  • 降低事件的触发频率
  • 类似于技能冷却中,比如调用某个函数之后,一段时间内不能再次调用

对一个技能进行冷却操作

const flash = function () {
  alert("回城了");
};
​
let coolDown = false;
​
const useSkill = function () {
  // 如果处于冷却中,那么直接返回
  if (coolDown) return;
  // 执行技能
  flash();
  // 技能冷却了
  coolDown = true;
  // 3秒之后,冷却时间才结束
  setTimeout(() => {
    coolDown = false;
  }, 3000);
};
​
useSkill();

如果对于任何技能,进行任意时间的冷却

const flash = function () {
  console.log("闪现了");
};
​
let coolDownFn = function (skillFn, coolDownTime) {
    let coolDown = false;
  return function (...args) {
    if (coolDown) return;
    skillFn(...args);
    coolDown = true;
    setTimeout(() => {
      coolDown = false;
    }, coolDownTime * 1000);
  };
};
​
const x = coolDownFn(flash, 10);
x("李");

改成标准的throttle就可以了

const flash = function (name) {
  console.log("闪现了");
  console.log(name);
};
​
let throttle = function (skillFn, coolDownTime) {
  let coolDown = false;
  return function (...args) {
    if (coolDown) return;
    skillFn(...args); // 获得参数并执行
    coolDown = true;
    setTimeout(() => {
      coolDown = false;
    }, coolDownTime * 1000);
  };
};
​
const x = throttle(flash, 10);
x("李");

只用timer的实现节流

应用在什么地方(使用场景)

  • 避免用户频繁点击触发对应功能
  • 可以用在抢购上,例如每5秒钟只能点一次抢购

防抖

什么是防抖,举个例子

  • 防抖就类似于回城功能被打断
  • 回城被打断就重新计时

对一个回城功能进行打断操作

const townGate = function () {
  console.log("回城成功");
};
​
let timer = null;
​
function useTownGate() {
  if (timer) clearTimeout(timer);
  timer = setTimeout(() => {
     console.log(timer)
    townGate();
    timer = null;
  }, 3000);
}
​
useTownGate();

对任意功能进行打断操作

const townGate = function() {
    console.log('回城')
}
​
const createFn = function(fn, time) {
    let timer = null;
    return function(...args) {
        if(timer) clearTimeout(timer)
        timer = setTimeout(() => {
            fn(...args)
            timer = null
        },time*1000)
    }
}
​
const x = createFn(townGate,5)
x()

应用在什么地方(使用场景)

  • 比如鼠标滑动事件mousemove,等待设定时间后,在执行对应的事件