用网游的设定解释JavaScript手写节流和防抖

98 阅读1分钟

节流throttle

节流的核心思想,用一个例子可以生动地说清楚,那就是游戏中的释放技能后会有技能冷却的时间,在这段时间内,用户无法重复发起请求,以达到节流的效果。

const kill = () => {
    // kill
}

const throttle = (fn, time) => { // 传入技能名和冷却时间
    let timer = null;
    return (...args) => {
        if (timer) {
            return;
        }
        kill();
        timer = setTimeOut(()=>{
            timer = null;
        }, time)
    }
}

const main_skill = throttle(kill, 360 * 1000);

main_skill(arg1,arg2,arg3);

在上述代码中,我们可以通过判断timer是否存在,来检验是否处于技能冷却时间段内。

有几种不同方案:

  1. 计时器(如上代码)
  2. 时间戳

应用场景:

  1. 用户频繁按钮点击(下单/抢购)

防抖debounce

bounce直译为弹跳/反弹,debounce直译为去弹跳。防抖就相当于游戏中回城被打断,需要重新发起回城请求。

const arrival = () => {
    // go home
} 

const debounce = (fn, time) => {
    let timer = null;
    return (...args) => {
        if (timer) { // 再次调用debounce时
            clearTimeOut(timer);
        }
        timer = setTimeOut(()=>{
            fn(...args);
            timer = null;
        }, time)
    }
    
}

const departure = debounce(arrival, 6 * 1000)

有几种不同方案:

  1. 计时器(如上代码)
  2. 时间戳

应用场景:

  1. 用户频繁拖动改变页面大小

总结

throttle和debounce其实是从两个方面去限制用户频繁操作带来的负面影响,前者是锁定一段时间拦截住用户的操作,后者是每次用户操作就重新计时。